標籤:
http://www.cnblogs.com/void/archive/2012/02/01/2335224.html
優先隊列是隊列的一種,不過它可以按照自訂的一種方式(資料的優先順序)來對隊列中的資料進行動態排序
每次的push和pop操作,隊列都會動態調整,以達到我們預期的方式來儲存。
例如:我們常用的操作就是對資料排序,優先隊列預設的是資料大的優先順序高
所以我們無論按照什麼順序push一堆數,最終在隊列裡總是top出最大的元素。
用法:
樣本:將元素5,3,2,4,6依次push到優先隊列中,print其輸出。
1. 標準庫預設使用元素類型的<操作符來確定它們之間的優先順序關係。
priority_queue<int> pq;
通過<操作符可知在整數中元素大的優先順序高。
故樣本1中輸出結果為: 6 5 4 3 2
2. 資料越小,優先順序越高
priority_queue<int, vector<int>, greater<int> >pq;
其中
第二個參數為容器類型。
第二個參數為比較函數。
故樣本2中輸出結果為:2 3 4 5 6
3. 自訂優先順序,重載比較符號
重載預設的 < 符號
struct node
{
friend bool operator< (node n1, node n2)
{
return n1.priority < n2.priority;
}
int priority;
int value;
};
這時,需要為每個元素自訂一個優先順序。
註:重載>號會編譯出錯,因為標準庫預設使用元素類型的<操作符來確定它們之間的優先順序關係。
而且自訂類型的<操作符與>操作符並無直接聯絡
代碼:
1 #include<iostream>
2 #include<functional>
3 #include<queue>
4 using Namespace stdnamespace std;
5 struct node
6 {
7 friend bool operator< (node n1, node n2)
8 {
9 return n1.priority < n2.priority;
10 }
11 int priority;
12 int value;
13 };
14 int main()
15 {
16 const int len = 5;
17 int i;
18 int a[len] = {3,5,9,6,2};
19 //樣本1
20 priority_queue<int> qi;
21 for(i = 0; i < len; i++)
22 qi.push(a[i]);
23 for(i = 0; i < len; i++)
24 {
25 cout<<qi.top()<<" ";
26 qi.pop();
27 }
28 cout<<endl;
29 //樣本2
30 priority_queue<int, vector<int>, greater<int> >qi2;
31 for(i = 0; i < len; i++)
32 qi2.push(a[i]);
33 for(i = 0; i < len; i++)
34 {
35 cout<<qi2.top()<<" ";
36 qi2.pop();
37 }
38 cout<<endl;
39 //樣本3
40 priority_queue<node> qn;
41 node b[len];
42 b[0].priority = 6; b[0].value = 1;
43 b[1].priority = 9; b[1].value = 5;
44 b[2].priority = 2; b[2].value = 3;
45 b[3].priority = 8; b[3].value = 2;
46 b[4].priority = 1; b[4].value = 4;
47
48 for(i = 0; i < len; i++)
49 qn.push(b[i]);
50 cout<<"優先順序"<<‘\t‘<<"值"<<endl;
51 for(i = 0; i < len; i++)
52 {
53 cout<<qn.top().priority<<‘\t‘<<qn.top().value<<endl;
54 qn.pop();
55 }
56 return 0;
57 }
【轉】優先隊列priority_queue 用法詳解