1. 程式人生 > >優先佇列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 //示例120 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 //示例230 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 //示例340 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 }