priority_queue優先佇列 按照由小到大順序
C++優先佇列的基本使用方法
在優先佇列中,優先順序高的元素先出佇列。
標準庫預設使用元素型別的<操作符來確定它們之間的優先順序關係。
優先佇列的第一種用法,也是最常用的用法:
1.佇列從大到小
priority_queue<int> qi;
通過<操作符可知在整數中元素大的優先順序高。
故示例1中輸出結果為:9 6 5 3 2
2.把元素從小到大輸出,這時我們可以傳入一個比較函式,使用functional.h函式物件作為比較函式。
priority_queue<int, vector<int>, greater<int> >qi2;
其中 第二個引數為容器型別。 第二個引數為比較函式。
故示例2中輸出結果為:2 3 5 6 9
3.自定義優先順序。
struct node
{
friend bool operator< (node n1, node n2)
{
return n1.priority < n2.priority;
}
int priority;int value;
};
在該結構中,value為值,priority為優先順序。
通過自定義operator<操作符來比較元素中的優先順序。
在示例3中輸出結果為:
優先順序 值
9 5
8 2
6 1
2 3
1 4
但如果結構定義如下:
struct node
{
friend bool operator> (node n1, node n2)
{
return n1.priority > n2.priority;
}
int priority;
int value;
};
則會編譯不過(G++編譯器)
因為標準庫預設使用元素型別的<操作符來確定它們之間的優先順序關係。
而且自定義型別的<操作符與>操作符並無直接聯絡,故會編譯不過。
//程式碼清單
#include<iostream>
#include<functional>
#include<queue>
using Namespace stdnamespace std;
struct node
{
friend bool operator< (node n1, node n2)
{
return n1.priority < n2.priority;
}
int priority;
int value;
};
int main()
{
const int len = 5;
int i;
int a[len] = {3,5,9,6,2};
//示例1
priority_queue<int> qi;
for(i = 0; i < len; i++)
qi.push(a[i]);
for(i = 0; i < len; i++)
{
cout<<qi.top()<<" ";
qi.pop();
}
cout<<endl;
//示例2
priority_queue<int, vector<int>, greater<int> >qi2;
for(i = 0; i < len; i++)
qi2.push(a[i]);
for(i = 0; i < len; i++)
{
cout<<qi2.top()<<" ";
qi2.pop();
}
cout<<endl;
//示例3
priority_queue<node> qn;
node b[len];
b[0].priority = 6; b[0].value = 1;
b[1].priority = 9; b[1].value = 5;
b[2].priority = 2; b[2].value = 3;
b[3].priority = 8; b[3].value = 2;
b[4].priority = 1; b[4].value = 4;
for(i = 0; i < len; i++)
qn.push(b[i]);
cout<<"優先順序"<<'\t'<<"值"<<endl;
for(i = 0; i < len; i++)
{
cout<<qn.top().priority<<'\t'<<qn.top().value<<endl;
qn.pop();
}
return 0;、
}
本文個別程式碼轉載,如有侵權,請聯絡刪除。