您的位置:首页 > 其它

STL 优先队列 用法

2019-07-26 00:25 1446 查看

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

需要的库

#include<queue>
using namespace std;

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

定义

priority_queue<Type, Container, Functional>

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

Container是容器类型默认是vector

Functional是比较的方式  比如greater<int>   less<int>   或者自己定义的比较函数

具体用法

基本用法1

priority_queue <int> q;

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

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

基本用法2

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

因为声明了比较的方式,这次必须要传三个参数进去了

需要注意的是:

  • 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 交换内容
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: