用堆结构实现的优先队列priority_queue
优先队列具有队列的所有特性,在这基础上添加了内部的一个排序,本质是堆实现的
参数模版
//priority_queue< type, container, function >
这三个参数,后面两个可以省略,第一个不可以。
其中:
- type:数据类型;
- container:实现优先队列的底层容器;
- function:元素之间的比较方式;
对于container,要求必须是数组形式实现的容器,例如vector、deque,而不能使list。
在STL中,默认情况下(不加后面两个参数)是以vector为容器,以 operator< 为比较方式,所以在只使用第一个参数时,优先队列默认是一个最大堆,每次输出的堆顶元素是此时堆中的最大元素。
成员函数
假设type类型为int
,则:
bool empty() const
返回值为true,说明队列为空;int size() const
返回优先队列中元素的数量;void pop()
删除队列顶部的元素,也即根节点int top()
返回队列中的顶部元素,但不删除该元素;void push(int arg)
将元素arg插入到队列之中;
1.当使用基本数据类型(如int)时
需要注意的是,如果使用less<int>
和greater<int>
,需要头文件:
#include <functional>
//默认大顶堆
priority_queue<int> a;
//升序队列,小顶堆
priority_queue <int,vector<int>,greater<int> > q;
//降序队列
priority_queue <int,vector<int>,less<int> >q;
//greater和less是std实现的两个仿函数(就是使一个类的使用看上去像一个函数。其实现就是类中实现一个operator(),这个类就有了类似函数的行为,就是一个仿函数类了)
2.对于自定义类型,需要对运算符重载、重写仿函数
//方法1(仍然利用默认funtional,但是需要重载其中的 <运算符 来实现对自定义类型的比较)(这种方法只能使用带一个参数的模版声明对象,不能使用less<tmp1>和greater<tmp1>,)
struct tmp1 //运算符重载<
{
int x;
tmp1(int a) {x = a;}
bool operator<(const tmp1& a) const
{
return x < a.x; //大顶堆
}
};
tmp1 a(1);
tmp1 b(2);
tmp1 c(3);
priority_queue<tmp1> d;//priority_queue<tmp1,vector<tmp1>
d.push(b);
d.push(c);
d.push(a);
//此时d.top == c(3)
//方法2(可以使用带三个参数的模版声明对象了)
struct tmp1 //运算符重载<
{
int x;
tmp1(int a) {x = a;}
bool operator<(const tmp1& a) const
{
return x < a.x; //大顶堆
}
};
struct cmp //重写仿函数
{
bool operator() (tmp1 a, tmp1 b)
{
return a.x < b.x; //大顶堆
}
};
priority_queue<rmp1,vector<tmp1>,tmp2> f;
参考文章:
https://blog.csdn.net/lym940928/article/details/89635690