一直都想知道,priority_queue与queue的区别是啥,一直问别人,总找不到自己要的答案,哇,今天我在做一道题时,哈,又发现它,来说一说。
priority_queue是动态队列,每次弹出都会重新按照自定义排序进行重新编排。默认的是判断大小的符号是"<",数据大的优先,它与“>”一定要区分开,当你重载运算符时,只允许对"<"进行重载
为了更好的说明,我们先看常规的默认效果;
#include<iostream>
#include<queue>
#include<string>
using namespace std;
const int M=100;
struct node{
string name;
int cost;
node(string str,int co){
name=str;
cost=co;
}
friend bool operator<(const node &a,const node &b){
return a.cost<b.cost;//注意! 数据大的优先
}
};
string nm[M];
string yourName;
int yourCost;
int yourYard;
int cs[M];
priority_queue<node> q[4];
int main()
{
int n,t;
cin>>n;
cout<<"please intput "<<n<<"the name ,the const,the yard of people"<<endl;
for(int i=0;i<n;i++){
cin>>yourName>>yourCost>>yourYard;
q[yourYard].push(node(yourName,yourCost));
}
cout<<"--------------------------"<<endl;
for(int i=1;i<=3;i++){
cout<<"yard"<<i<<":"<<endl;
while(!q[i].empty()){
cout<<q[i].top().name<<" "<<q[i].top().cost<<endl;
q[i].pop();
}
}
return 0;
}
/*
10
西西 5000 1
谷谷 7000 1
丰真 6500 2
悠悠 8700 2
咕咕 10000 3
霉西 10000 1
小谷 7800 1
小飞 5500 2
小哟 9900 2
米菲 12000 3
*/
接下来我们更改优先级
#include<iostream>
#include<queue>
#include<string>
using namespace std;
const int M=100;
struct node{
string name;
int cost;
node(string str,int co){
name=str;
cost=co;
}
friend bool operator<(const node &a,const node &b){
return b.cost<a.cost;//注意! 数据小的优先
}
};
string nm[M];
string yourName;
int yourCost;
int yourYard;
int cs[M];
priority_queue<node> q[4];
int main()
{
int n,t;
cin>>n;
cout<<"please intput "<<n<<"the name ,the const,the yard of people"<<endl;
for(int i=0;i<n;i++){
cin>>yourName>>yourCost>>yourYard;
q[yourYard].push(node(yourName,yourCost));
}
cout<<"--------------------------"<<endl;
for(int i=1;i<=3;i++){
cout<<"yard:"<<i<<endl;
while(!q[i].empty()){
cout<<q[i].top().name<<" "<<q[i].top().cost<<endl;
q[i].pop();
}
}
return 0;
}
/*
10
西西 5000 1
谷谷 7000 1
丰真 6500 2
悠悠 8700 2
咕咕 10000 3
霉西 10000 1
小谷 7800 1
小飞 5500 2
小哟 9900 2
米菲 12000 3
*/