我们知道,
priority_queue<int>是默认的大堆根序列,自动从大到小排序
priority_queue<int,vector<int>,greater<int>>是最小值的优先序列,自动从小到大的排序。
以上两者只有一个元素,那么对于priority_queue<pair<int,int>,vector<pair<int,int>>,greater<pair<int,int>>> q,存在有两种元素的排列顺序又是怎样的呢?
先上结论:编译器会根据pair<>的first成员进行排序。
#include <iostream>
#include <queue>
#include <vector>
using namespace std;
typedef pair<int,int> PII;
priority_queue<PII,vector<PII>,greater<PII>> q;
int main()
{
//入队一个pair元素,value递减,key递增
q.push({10,2});
q.push({9,4});
q.push({8,6});
q.push({7,8});
q.push({6,10});
//入队一个pair元素,value递增,key递减
q.push({5,9});
q.push({4,7});
q.push({3,5});
q.push({2,3});
q.push({1,1});
for(int i=1;i<=10;i++)
{
cout<<q.top().first<<" "<<q.top().second<<endl;
q.pop();//
}
return 0;
}
输出为:
1 1
2 3
3 5
4 7
5 9
6 10
7 8
8 6
9 4
10 2