和队列的基本操作相同。
image.png
queue容器的返回第一个元素操作为front()
定义:priority_queue

参数说明

Type:是数据类型
Container:容器类型(默认vector)
Functional:比较的方式,默认为大顶堆

这里千万注意,greater是小顶堆
less是大顶堆

  1. 1 //升序队列,小顶堆
  2. 2 priority_queue <int,vector<int>,greater<int> > q;
  3. 3 //降序队列,大顶堆
  4. 4 priority_queue <int,vector<int>,less<int> >q;
  5. 5
  6. 6 //greater和less是std实现的两个仿函数(就是使一个类的使用看上去像一个函数。其实现就是类中实现一个operator(),这个类就有了类似函数的行为,就是一个仿函数类了)

普通用法

  1. int main(){
  2. priority_queue<int> a;
  3. priority_queue<int, vector<int>, greater<int>> b;
  4. for(int i=0;i<5;i++)
  5. b.push(i);
  6. while(!b.empty()){
  7. cout<<b.top()<<" ";
  8. b.pop();
  9. }
  10. }

pair比较

  1. #include <iostream>
  2. #include<vector>
  3. #include<queue>
  4. using namespace std;
  5. int main(){
  6. priority_queue<pair<int,int>> pq;
  7. pq.push(make_pair(3,5));//make_pair()是函数。
  8. pq.push(make_pair(4,6));
  9. pq.push(make_pair(1,7));
  10. while(!pq.empty()){
  11. cout<<pq.top().first<<" "<<pq.top().second<<endl;
  12. pq.pop();
  13. }
  14. return 0;
  15. }

自定义类型

定义小顶堆;

  1. static bool cmp(pair<int,int> a,pair<int,int> b){
  2. return a.second>b.second; //这里是>号,千万注意priority_queue的cmp是反过来的。
  3. }
  4. priority_queue<pair<int,int>,vector<pair<int,int>>,decltype(&cmp)> pq(cmp); //这里的Pq(cmp)是构造函数初始化。

其中priority_queue的模板有三个参数:

  • 第一个是元素类型
  • 第二个是容器类型
  • 第三个是Compare,是size_type类型的,无符号整型。

priority_queue的构造函数的参数中有comp,表示用于排序堆的比较对象。默认是less大顶堆。如果是自定义的比较函数,那么需要向如上声明。
当要自定义比较函数时,大于小于号的确定: