優先隊列priority_queue 用法詳解


優先隊列是隊列的一種,不過它可以按照自定義的一種方式(數據的優先級)來對隊列中的數據進行動態的排序

每次的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 }

轉載自:vvilp,有改動


免責聲明!

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



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