priority_queue<int> q;//默認優先級隊列的定義。
在默認的優先隊列中,優先級高的先出隊。在默認的int型中先出隊的為較大的數。
#include <iostream> #include <vector> #include <queue> using namespace std; struct cmp{ bool operator()(int &a,int &b){ return a > b; //最小值優先 } }; struct cmp1{ bool operator()(int &a,int &b){ return a < b; //最大值優先 } }; int a[] = {2,5,3,6,7,1,9,6,4}; int main() { priority_queue<int,vector<int>,cmp> q; priority_queue<int,vector<int>,cmp1> q1; //自定義優先級 priority_queue<int,vector<int>,greater<int> > q2; //內定義優先級(最小值) priority_queue<int,vector<int>,less<int> > q3; //(最大值) for(int i = 0;a[i];i++){ q.push(a[i]); q1.push(a[i]); q2.push(a[i]); q3.push(a[i]); } cout<<q.size()<<endl; cout<<"最小值優先"<<endl; while(!q.empty()) { cout<<q.top()<<" "; q.pop(); } cout<<"\n"; cout<<"最大值優先"<<endl; while(!q1.empty()){ cout<<q1.top()<<" "; q1.pop(); } cout<<"\n"; cout<<"最小值優先"<<endl; while(!q2.empty()){ cout<<q2.top()<<" "; q2.pop(); } cout<<"\n"; cout<<"最大值優先"<<endl; while(!q3.empty()){ cout<<q3.top()<<" "; q3.pop(); } cout<<"\n"; return 0; }
運行結果:
9
最小值優先
1 2 3 4 5 6 6 7 9
最大值優先
9 7 6 6 5 4 3 2 1
最小值優先
1 2 3 4 5 6 6 7 9
最大值優先
9 7 6 6 5 4 3 2 1
第二種自定義優先級:
struct number1{ int x; bool operator < (const number1 &a) const { return x>a.x;//最小值優先 } }; number1 num1[]={14,10,56,7,83,22,36,91,3,47,72,0}; int main() { priority_queue<number1>q; for(i=0;num1[i].x;i++) q.push(num1[i]); while(!q.empty()){
cout<<q.top()<<" ";
q.pop();
}
cout<<"\n";
}
