优先队列priority_queue
一种能够自动排序的队列。
priority_queue两种用法
priority(存放类型 , 存放数组 , 排序规则)
#include
priority_queue
priority_queue
//less
priority_queue
//greater是从小到大
基本函数用法
与普通队列相同
q.size();//返回q里元素个数
q.empty();//返回q是否为空,空则返回1,否则返回0
q.push(k);//在q的末尾插入k
q.pop();//删掉q的第一个元素
q.top();//返回q的第一个元素
结构体重载小于
struct node
{
int x , y;
bool operator < (const node & a)const
{
return x < a.x;
}
}k
priority_queue
//此时输出是按x的大小从大到小输出
此时输出是按x的大小从大到小输出
使用结构体自定义排序
int n;
struct node
{
int fir,sec;
void Read() {scanf("%d %d",&fir,&sec);}
}input;
struct cmp1
{
bool operator () (const node &x,const node &y) const
{
return x.fir } };//当一个node x的fir值小于另一个node y的fir值时,称x priority_queue /////////////////////////////////////////////与上面程序相同效果的sort自定义排序 struct node { int fir,sec; }arr[2030]; bool cmp1(node x,node y) { return x.fir } sort(arr+1,arr+1+n,cmp1); sort重载小于号和优先队列结构体重载小于号区别!!! #include using namespace std; struct node{ string name; int price; bool operator < (const node &a)//!!!!这里一定是重载小于号,否则重载大于号会报错 //因为priority_queue const { return price < a.price; } }k; struct node2{ string name; int price; }fruit2[100]; priority_queue bool cmp(node2 a , node2 b){//sort自定义排序 return a.price > b.price; } void solve(){ int n; cin >> n; string fruitname; int fruitprice; for(int i =1 ; i <= n; i++){ cin >>fruit2[i].name >> fruit2[i].price; k.name = fruit2[i].name; k.price = fruit2[i].price; fruit1.push(k);//队列用push存取数据 } while(!fruit1.empty()) { fruitname = fruit1.top().name ; fruitprice = fruit1.top().price; fruit1.pop(); cout << fruitname << " " << fruitprice < } cout << endl; sort(fruit2+1 ,fruit2 + 6 , cmp ); for(int i = 1; i <= n ; i++) { cout << fruit2[i].name << " " << fruit2[i].price < } cout << endl; return; } signed main(){ int t = 1; //cin >> t; while(t--){ solve(); } return 0; } /* 输入: 5 apple 10 banana 12 orange 22 watermelon 30 peer 100 输出: peer 100 watermelon 30 orange 22 banana 12 apple 10 peer 100 watermelon 30 orange 22 banana 12 apple 10 */ //如果实现优先队列结构体从小到大: struct node{ string name; int price; bool operator < (const node &a)const { return price > a.price; } }k; /* 输出: apple 10 banana 12 orange 22 watermelon 30 peer 100 */ 解释: bool operator < (const node &a) const { return price < a.price; } < : 优先输出级低 < 优先输出级高 当 当前price > a.price ,程序返回true ,及确认 当前price优先输出级 < a.price优先输出级 a的price会优先输出,实现从大到小 bool operator < (const node &a) const { return price > a.price; } 此时price > a.price;成立则还是a优先输出,只不过此时更小的元素a.price先被输出,优先队列实现从小到大排序。 不同写法 2.重载 struct node{ int val; bool operator <(const node &b) const{ return val > b.val; } }; struct node{ int val; friend bool operator <(const node &a, const node &b){ return a.val > b.val; } }; struct node{ int val; }; bool operator <(const node &a, const node &b){ return a.val > b.val; } 上面三种方式都是按照数据从小到大的方式输出