STL 优先队列 用法

今天作题用到了优先队列 对它的用法还不是很熟悉 如今整理一下。node

须要的库

#include<queue>
using namespace std;

 不过我都用bits/stdc++.h...c++

定义

priority_queue<Type, Container, Functional>数据结构

Type是数据的类型 好比int啊char啊之类的less

Container是容器类型默认是vector函数

Functional是比较的方式  好比greater<int>   less<int>   或者本身定义的比较函数spa

具体用法

基本用法1

priority_queue <int> q;

这是最基本的用法 不须要像定义同样传三个参数进去 只须要声明一个数据类型便可设计

须要注意的是 优先队列是默认从大到小排的!code

基本用法2

//升序队列
priority_queue <int,vector<int>,greater<int> > q;
//降序队列
priority_queue <int,vector<int>,less<int> >q;

由于声明了比较的方式,此次必需要传三个参数进去了blog

须要注意的是:排序

  • greater<int>  和 > 之间必需要有一个空格,否则是右移运算符!
  • greater是升序排列,也就是从小到大排,不是咱们想固然的greater就是从大到小!(因此这里只须要记住 greater是升序 up up~ less是降序down down~ 这样比较符合正常人的认知,也好记~)

进阶用法1(运算符重载)

方法1 使用 friend bool operator

typedef struct node
{
    int num;
    friend bool operator < (const node & a,const node & b)
    {
        return a.num < b.num ;
    }    
}point;

 priority_queue<point>q;
 

这个方法是将运算符的重载在结构体的定义中完成,优先队列的的定义中就不须要传三个参数了 在这个小例子里看起来没什么用 不过解决复杂问题时,就须要采用结构体来设计数据结构 也就必需要告诉计算机,比较的方式。

须要注意的是:

  • 只能对小于号进行重载
  • 若想从小到大排 只须要将return语句的小于号改为大于号便可 和sort是正好反过来的!

方法2 使用 bool operator

typedef struct node
{
        int num;
        bool operator<(const node&b)const        
        {
            return    num<b.num;
        }
}point;    

priority_queue<point>q;

和采用friend bool operator的方法1同样,只是写法略有不一样 我不喜欢用 感受乱乱的....

进阶用法2(重写仿函数)

struct node1 
{
    int x;
};

struct node2 
{
    bool operator() (node1 a, node1 b) 
    {
        return a.x < b.x; 
    }
};

priority_queue<node1, vector<node1>, node2> p;

重写仿函数这个用起来真麻烦呀....须要声明两个结构体 不喜欢用....

支持的操做

  • top 访问队头元素
  • empty 队列是否为空
  • size 返回队列内元素个数
  • push 插入元素到队尾 (并排序)
  • emplace 原地构造一个元素并插入队列
  • pop 弹出队头元素
  • swap 交换内容
相关文章
相关标签/搜索