priority_queue 又称为优先队列,其底层是用堆来进行实现的。
在优先队列中,队首元素一定是当前队列中优先级最高的那一个。
可以在任何时候往优先队列里面加入 (push) 元素,而优先队列底层的数据结构堆 (heap) 会随时调整结构,使得每次的队首元素都是优先级最大的。
1.定义
//头文件
#include <queue>
using namespace std;
priority_queue<Type, Container, Functional>;
Type 是数据类型,可以是任意基本数据类型或容器;Container 是容器类型(Container必须是用数组实现的容器,比如vector,deque等等,但不能用 list。STL里面默认用的是vector),Functional 是比较的方式,当需要用自定义的数据类型时才需要传入这三个参数,使用基本数据类型时,只需要传入数据类型,默认是大顶堆。
2. 队列中元素访问的基本操作
top 访问队头元素
empty 队列是否为空
size 返回队列内元素个数
push 插入元素到队尾 (并排序)
emplace 原地构造一个元素并插入队列
pop 弹出队头元素
swap 交换内容
3. 元素优先级的设置
3.1基本数据类型
int 型、double 型、char 型等可以直接使用的数据类型,优先队列对它们的优先级设置一般是数字大的优先级越高,因此队首元素就是优先队列内元素最大的那个(如果 char 型,则是字典序最大的)。
以int型为例:
priority_queue<int> q; //默认大顶堆
priority_queue<int,vector<int>,less<int>> q; //大顶堆
//vector<int>(也就是第二个参数)填写的是来承载底层数据结构堆(heap)的容器,
//如果第一个参数是 double 型或 char 型,则此处只需要填写 vector<double> 或 vector<char>;
priority_queue <int,vector<int>,greater<int> >q; //小顶堆
第三个参数 less<int> 是对第一个参数的比较类
//less<int> 表示数字大的优先级越大,而 greater<int> 表示数字小的优先级越大
示例:
#include <queue>
using namespace std;
int main()
{
priority_queue<int,vector<int>,greater<int>> q;
q.push(3);
q.push(4);
q.push(1);
cout<<q.top()<<endl;
return 0;
}
//输出为 1 ,即队首元素为1
3.2自定义优先级设置
通过自定义结构体,重载运算符来实现,举个例子:
#include <iostream>
#include<string>
#include <queue>
using namespace std;
struct fruit {
string name;int price;
}f1,f2,f3;
struct cmp { //自定义结构体
bool operator ()(const fruit& fl,const fruit& f2) //重载"<"
{
//这里表示价格小的优先级小
return f1.price < f2.price;
//如果return f1.price > f2.price,则价格大的优先级小
}
};
int main()
{
priority_queue<fruit,vector<fruit>,cmp> q;
f1.name = "桃子";
f1.price = 3;
f2.name ="梨子";
f2.price = 4;
f3.name="苹果";
f3.price = 1;
q.push (f1);
q.push(f2);
q.push(f3);
cout<<q.top().name <<"" <<q.top().price <<endl;
return 0;
}
//输出梨子4