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;


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM