priority_queue的使用

priority_queue本质是一个堆。

  1. 头文件是#include
  2. 关于模板参数
      模板申明带3个参数:priority_queue<Type, Container, Functional>

Type 为数据类型
Container为保存数据的容器:必须是用数组实现的容器,比如vector,deque等等,但不能用 list。STL里面默认用的是vector。
Functional 为元素比较方式:比较方式默认用operator<,所以如果把后面2个参数缺省的话,优先队列就是大顶堆(降序),队头元素最大。特别注意pair的比较函数。

//返回降序输入
#include <iostream>
#include <queue>
using namespace std;
int main(){
    priority_queue<int> q;
    for( int i= 0; i< 10; ++i ) q.push(i);
    while( !q.empty() ){
        cout<<q.top()<<endl;
        q.pop();
    }
    return 0;
}

关于优先级队列priority_queue之比较函数
在这里插入图片描述
常用为

greater<> //升序
priority_queue<int, vector<int>, greater<int> > q;

可以以自定义比较函数
但必须重载operator<或者重写仿函数
返回true时,说明左边形参的优先级低于右边形参

struct cmp{
    bool operator() ( int a , int b ){
return a< b;      //与greater是等价的
         }
};

priority_queue<int,vector<int>,cmp > p;

复杂一点的例子
小顶堆,先按x升序,x相等时,再按y升序

#include <iostream>
#include <queue>
using namespace std;
struct Node{
    int x, y;
    Node( int a= 0, int b= 0 ):
        x(a), y(b) {}
};
struct cmp{
    bool operator() ( Node a, Node b ){//默认是less函数
        //返回true时,a的优先级低于b的优先级(a排在b的后面)
        if( a.x== b.x ) return a.y> b.y;      
        return a.x> b.x; }
};
int main(){
    priority_queue<Node, vector<Node>, cmp> q;
    for( int i= 0; i< 10; ++i )
    q.push( Node( rand(), rand() ) );
    while( !q.empty() ){
        cout << q.top().x << ' ' << q.top().y << endl;
        q.pop();
    }
    return 0;
}

priority_queue的操作
在这里插入图片描述
本文参考https://www.cnblogs.com/Deribs4/p/5657746.html
更多资料在http://c.biancheng.net/view/480.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

王蒟蒻

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值