和队列的基本操作相同。
queue容器的返回第一个元素操作为front()
定义:priority_queue
参数说明
Type:是数据类型
Container:容器类型(默认vector)
Functional:比较的方式,默认为大顶堆
这里千万注意,greater
less
1 //升序队列,小顶堆
2 priority_queue <int,vector<int>,greater<int> > q;
3 //降序队列,大顶堆
4 priority_queue <int,vector<int>,less<int> >q;
5
6 //greater和less是std实现的两个仿函数(就是使一个类的使用看上去像一个函数。其实现就是类中实现一个operator(),这个类就有了类似函数的行为,就是一个仿函数类了)
普通用法
int main(){
priority_queue<int> a;
priority_queue<int, vector<int>, greater<int>> b;
for(int i=0;i<5;i++)
b.push(i);
while(!b.empty()){
cout<<b.top()<<" ";
b.pop();
}
}
pair比较
#include <iostream>
#include<vector>
#include<queue>
using namespace std;
int main(){
priority_queue<pair<int,int>> pq;
pq.push(make_pair(3,5));//make_pair()是函数。
pq.push(make_pair(4,6));
pq.push(make_pair(1,7));
while(!pq.empty()){
cout<<pq.top().first<<" "<<pq.top().second<<endl;
pq.pop();
}
return 0;
}
自定义类型
定义小顶堆;
static bool cmp(pair<int,int> a,pair<int,int> b){
return a.second>b.second; //这里是>号,千万注意priority_queue的cmp是反过来的。
}
priority_queue<pair<int,int>,vector<pair<int,int>>,decltype(&cmp)> pq(cmp); //这里的Pq(cmp)是构造函数初始化。
其中priority_queue的模板有三个参数:
- 第一个是元素类型
- 第二个是容器类型
- 第三个是Compare,是size_type类型的,无符号整型。
priority_queue的构造函数的参数中有comp,表示用于排序堆的比较对象。默认是less
当要自定义比较函数时,大于小于号的确定: