C++ 優先隊列priority_queue用法【轉載】

來源:互聯網
上載者:User

標籤:

priority_queue 對於基本類型的使用方法相對簡單。他的模板聲明帶有三個參數,priority_queue<Type, Container, Functional>
Type 為資料類型, Container 為儲存資料的容器,Functional 為元素比較方式。
Container 必須是用數組實現的容器,比如 vector, deque 但不能用 list.
STL裡面容器預設用的是 vector. 比較方式預設用 operator< , 所以如果你把後面倆個參數 預設的話,優先隊列就是大頂堆,隊頭元素最大。
看例子

 1 #include <iostream> 2 #include <queue> 3 using namespace std; 4 int main(){ 5     priority_queue<int,vector<int>,less<int> >q;//使用priority_queue<int> q1;一樣 6     for(int i=0;i<10;i++)  7         q1.push(i); 8     while(!q1.empty()){ 9         cout<<q1.top()<< endl;10         q1.pop();11     }12     return 0;13 }

如果要用到小頂堆,則一般要把模板的三個參數都帶進去。
STL裡面定義了一個仿函數 greater<>,對於基本類型可以用這個仿函式宣告小頂堆
例子:

 1 #include <iostream> 2 #include <queue> 3 using namespace std; 4 int main(){ 5     priority_queue<int,vector<int>,greater<int> >q; 6     for(int i=0;i<10;i++)  7         q.push(i); 8     while(!q.empty()){ 9         cout<<q.top()<< endl;10         q.pop();11     }12     return 0;13 }

對於自訂類型,則必須自己重載 operator< 或者自己寫仿函數先看看例子:

 1 #include <iostream> 2 #include <queue> 3 using namespace std; 4 struct Node{ 5     int x, y; 6 }node; 7  bool operator<( Node a, Node b){ 8     if(a.x==b.x) return a.y>b.y; 9     return a.x>b.x;10 }11  int main(){12     priority_queue<Node>q;13     for(int i=0;i<10;i++){14         node.x=i;15         node.y=10-i/2;16         q.push(node);17     }    18     while(!q.empty()){19         cout<<q.top().x <<‘ ‘<<q.top().y<<endl;20         q.pop();21     }22     return 0;23 }

自訂類型重載 operator< 後,聲明對象時就可以只帶一個模板參數。
此時不能像基本類型這樣聲明priority_queue<Node, vector<Node>, greater<Node> >;
原因是 greater<Node> 沒有定義,如果想用這種方法定義
則可以按如下方式

例子:(個人喜歡這種方法,因為set的自訂比較函數也可以寫成這種形式)

 1 #include <iostream> 2 #include <queue> 3 using namespace std; 4 struct Node{ 5     int x, y; 6 }node; 7 struct cmp{ 8     bool operator()(Node a,Node b){ 9         if(a.x==b.x) return a.y>b.y;10         return a.x>b.x;}11 };12 13  int main(){14     priority_queue<Node,vector<Node>,cmp>q;15     for(int i=0;i<10;i++){16         node.x=i;17         node.y=10-i/2;18         q.push(node);    19     }    20     while(!q.empty()){21         cout<<q.top().x<<‘ ‘<<q.top().y<<endl;22         q.pop();23     }24     return 0;25 }

 轉載自Sup_Heaven

C++ 優先隊列priority_queue用法【轉載】

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.