priority_queue的優先級變化(結構體的寫法)


priority_queue的優先級變化(結構體的寫法)

在頭文件中加上#include <queue> 即可使用stl中的庫函數priority_queue,優先隊列默認的是從大到小的優先級,但是我們在實際使用的時候,往往需要改變優先級(比如從小到大的排列),這時候就需要改變優先級。


//定義結構,使用運算符重載,自定義優先級1  
struct cmp1{  
    bool operator ()(int &a,int &b){  
        return a>b;//最小值優先  
    }  
};  
struct cmp2{  
    bool operator ()(int &a,int &b){  
        return a<b;//最大值優先  
    }  
};  
//定義結構,使用運算符重載,自定義優先級2  
struct number1{  
    int x;  
    bool operator < (const number1 &a) const {  
        return x>a.x;//最小值優先  
    }  
};  
struct number2{  
    int x;  
    bool operator < (const number2 &a) const {  
        return x<a.x;//最大值優先  
    }  
};  

int main()  
{   priority_queue<int>que;//采用默認優先級構造隊列  
  
    priority_queue<int,vector<int>,cmp1>que1;//最小值優先  
    priority_queue<int,vector<int>,cmp2>que2;//最大值優先  
  
    priority_queue<int,vector<int>,greater<int> >que3;//注意“>>”會被認為錯誤,  greater為函數從大到小排序
                                                      //這是右移運算符,所以這里用空格號隔開  
    priority_queue<int,vector<int>,less<int> >que4;////最大值優先 less則相反


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM