记住优先队列都是反着来的
-
priority_queue q;
默认为由大到小 (与sort默认由小到大相反) -
priority_queue<int, std::vector, std::greater > q;
由小到大排序
/*
*
将 1-9 压入队列中
1. std::priority_queue<int> q; -> 从大到小排列
2. std::priority_queue<int, std::vector<int>, std::greater<int> > q2; ->从小到大
3.用 lambda 比较元素。//没理解
*/
#include <functional>
#include <queue>
#include <vector>
#include <iostream>
//using namespace std;
template<typename T> void print_queue(T& q) {
while(!q.empty()) {
std::cout << q.top() << " ";
q.pop();
}
std::cout << '\n';
}
int main() {
std::priority_queue<int> q;
for(int n : {1,8,5,6,3,4,0,9,7,2})
q.push(n);
//输出为 9 8 7 6 5 4 3 2 1 0
print_queue(q);
std::priority_queue<int, std::vector<int>, std::greater<int> > q2;
for(int n : {1,8,5,6,3,4,0,9,7,2})
q2.push(n);
//输出为0 1 2 3 4 5 6 7 8 9
print_queue(q2);
// 用 lambda 比较元素。
auto cmp = [](int left, int right) { return (left ^ 1) < (right ^ 1); };
std::priority_queue<int, std::vector<int>, decltype(cmp)> q3(cmp);
for(int n : {1,8,5,6,3,4,0,9,7,2})
q3.push(n);
//输出为8 9 6 7 4 5 2 3 0 1
print_queue(q3);
}
/*
output
9 8 7 6 5 4 3 2 1 0
0 1 2 3 4 5 6 7 8 9
8 9 6 7 4 5 2 3 0 1
*/
- 加入结构体的排序,并同时规定排序方式
struct node
{
int x,y;
}k;
struct cmp1 //另辟struct,排序自定义
{
bool operator () (const node & a,const node & b) const
{
if(b.x!=a.x) return b.x<a.x;
else return b.y>a.y;
}
};
很坑的一点就是优先队列的规则设定和最终出来的刚好相反,详情见下面代码实例
priority_queue <node,vector<node>,cmp1> q; //优先列队写法
#include<cstdio>
#include<queue>
#include<algorithm>
#include<iostream>
using namespace std;
struct node
{
int x,y;
}k;
bool cmp(int a,int b)
{
return a>b;
}
struct cmp1 //另辟struct,排序自定义
{
bool operator () (const node & a,const node & b) const
{
if(b.x!=a.x) return b.x<a.x;
else return b.y>a.y;
}
};
priority_queue <node,vector<node>,cmp1> q; //优先列队写法
int main()
{
int e[] = {5,4,8,2,6,7,9}; //7个
sort(e,e+7,cmp);
for(int i = 0;i<7;i++)
cout<<e[i]<<" ";
cout<<endl<<endl;
k.x=10,k.y=100; q.push(k);
k.x=12,k.y=60; q.push(k);
k.x=12,k.y=40; q.push(k);
k.x=6,k.y=80; q.push(k);
k.x=8,k.y=20; q.push(k);
while(!q.empty())
{
node m=q.top(); q.pop();
printf("(%d,%d) ",m.x,m.y);
}
}
输出为
- (6,80) (8,20) (10,100) (12,60) (12,40)
按照原本sort定义cmp的习惯输出应该是x轴由大到小,相同x轴由小到大,这里完全反过来,留意
ε=ε=ε=┏(゜ロ゜;)┛
本文介绍了C++中的优先队列,强调了其默认排序规则是从大到小,并提供了如何自定义排序规则以实现从小到大的示例。在处理结构体时,优先队列的排序行为可能与预期相反,文章通过代码实例展示了这一特性。
1217

被折叠的 条评论
为什么被折叠?



