c++优先队列自定义排序方式

c++优先队列自定义排序方式

priqority <node> priq
如何对自定义的数据类型排序?
方法1

struct node
{
    int to,cost;
    node(int x1,int x2)
    {
        to=x1;
        cost = x2;
    }
    friend bool operator<(const node &a , const node &b)
    {
        return a.cost>b.cost;   // ascending sort
    }

};
priority_queue<node>priq;
  • 在结构体内定义一个友元函数,重载<号 实现按照cost从小到大排序;
  • 传入两个参数,内部写> 实际上是从小到大排序与sort相反!
    方法2
struct node
{
    int to,cost;
    node(int x1,int x2)
    {
        to=x1;
        cost = x2;
    }
};
struct cmp
{
    bool operator() (const node &a,const node &b)
    {
        return a.cost > b.cost;
    }
};
priority_queue<node,vector<node>,cmp>priq;
落霞与孤鹜齐飞,秋水共长天一色
原文地址:https://www.cnblogs.com/star-and-me/p/8681434.html