當前位置:
首頁 >
优先队列priority_queue 用法详解
發布時間:2023/12/20
43
豆豆
生活随笔
收集整理的這篇文章主要介紹了
优先队列priority_queue 用法详解
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
優先隊列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 }轉載于:https://www.cnblogs.com/Drenight/p/8611337.html
總結
以上是生活随笔為你收集整理的优先队列priority_queue 用法详解的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: jquery 收藏技巧
- 下一篇: 总结反思