优先级队列priority_queue
默认使用vector作为容器,底层数据结构为堆。
操作函数与stack一样。
priority_queue<int> a; //默认为最大值优先级队列,即top元素最大。
a.push(5);
a.pop();
a.top();
a.empty(); //判断是否为空
可以自定义优先级:
priority_queue<int, vector<int>, cmp> p;
注:使用less或greater需要#include<functional>
#include<functional>
priority_queue<int, vector<int>, less<int>> p; //最大值优先级队列
priority_queue<int, vector<int>, greater<int>> p; //最小值优先级队列
定义cmp:
struct cmp
{
bool operator()(int &a, int &b) const
{
return a > b; //最小值优先
}
};
struct cmp
{
bool operator()(int &a, int &b) const
{
return a < b; //最大值优先
}
};
优先级队列的应用:定义一个元素为pair的优先级队列,自定义比较函数,使队列按照pair.first的大小排列,如果pair.first相等,则按照pair.second的大小排列。
#include<iostream>
#include<vector>
#include<queue>
using namespace std;
struct cmp
{
bool operator()(pair<int, int>&a, pair<int, int>&b) const
{
if(a.first == b.first) return a.second > b.second;
else return a.first < b.first;
}
};
int main(){
int n;
cin >> n;
priority_queue<pair<int, int>, vector<pair<int, int> >, cmp> p;
for(int i = 0; i < n; ++i){
int first, second;
cin >> first >> second;
p.push(make_pair(first, second));
}
while(p.size()){
cout << p.top().first << ' ' << p.top().second << endl;
p.pop();
}
return 0;
}
输出结果如下: