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