优先队列(初了解)

优先队列是自动排序

参考https://blog.csdn.net/qq_19656301/article/details/82490601

头文件

#include<queue>
using namespace std;

声明格式

priority_queue<结构类型> 队列名; 

比如(默认是从大到小的)

priority_queue <int> i;
priority_queue <double> d;

基本操作

q.size();//返回q里元素个数
q.empty();//返回q是否为空,空则返回1,否则返回0
q.push(k);//在q的末尾插入k
q.pop();//删掉q的第一个元素
q.top();//返回q的第一个元素
q.back();//返回q的末尾元素

默认的优先队列(结构体,重载小于)

在结构体里写是这个

struct node
{
    int x,y;
    bool operator < (const node & a) const
    {
        return x<a.x;
    }
};

不在结构体里

扫描二维码关注公众号,回复: 5175656 查看本文章
bool operator< (const node &a, const node &b){
    return a.x < b.x ;
}

priority_queue <int,vector<int>,less<int> > p;//从大到小
priority_queue <int,vector<int>,greater<int> > q;//从小到大

平时如果用从大到小不用后面的vector<int>,less<int>,可能到时候要改成从小到大,你反而会搞忘怎么写greater<int>,反而得不偿失

 

猜你喜欢

转载自www.cnblogs.com/yyys-/p/10390104.html
今日推荐