c++ 优先级队列
priority_queue
在默认的优先队列中,优先级高的先出队。在默认的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";}