1.优先级队列简介
优先级队列(priority_queue)是一种容器适配器,默认基础容器为数组vector,使用时需要包含头文件<queue>。其内部基于堆结构实现,关于堆结构的介绍可以看这里。理解了堆之后也就能理解优先级队列的原理,以及为什么使用vector作为默认基础容器,不过不了解堆结构也不影响优先级队列的使用。
优先队列是0个或多个元素的集合,每个元素都有一个优先权或值,对优先队列执行的操作有
1) 查找;
2) 插入一个新元素;
3) 删除.
在最小优先队列中,最小元素在最前面,可以通过top函数访问,删除操作用来删除该元素(此时内部构造最小堆),删除元素或插入新元素后同样保证最小元素在最前面这个特点;对于最大优先队列,最大元素在最前面,可以通过top函数访问,删除操作用来删除该元素(此时内部构造最大堆)。
2.成员函数
empty | 判断容器是否为空 |
size | 返回容器大小 |
top | 返回最前面的元素(即堆顶元素) |
push | 插入元素 |
emplace | 构造并插入元素 |
pop | 删除最前面元素(即堆顶元素) |
swap | 交换两个优先级队列 |
在进行插入删除等操作时,元素始终保持堆结构。
3.构造函数
#include <iostream> // std::cout
#include <queue> // std::priority_queue
#include <vector> // std::vector
#include <functional> // std::greater
using namespace std;
int main()
{
int myints[] = { 10,60,50,20 };
priority_queue<int> first;//默认构造大顶堆,基础容器为vector,相当priority_queue<int, vector<int>, less<int> >
priority_queue<int> second(myints, myints + 4);
cout << second.top() << endl;//此时输出最大元素60
priority_queue<int, vector<int>, greater<int> >
third(myints, myints + 4);//构造小顶堆
cout << third.top() << endl;//输出最小元素10
return 0;
}
4.自定义排序
#include <iostream> // std::cout
#include <queue> // std::priority_queue
#include <vector> // std::vector
using namespace std;
class mycomparison
{
bool reverse;//reverse为ture时构造小顶堆,为false时构造大顶堆
public:
mycomparison(const bool& revparam = false)
{
reverse = revparam;
}
bool operator() (const int& lhs, const int&rhs) const
{
if (reverse) return (lhs > rhs); //小顶堆
else return (lhs < rhs); //大顶堆
}
};
int main()
{
typedef priority_queue<int, vector<int>, mycomparison> mypq_type;
mypq_type fourth(myints, myints + 4); // 大顶堆
cout << fourth.top() << endl; //输出最大元素60
//mypq_type fifth(myints, myints + 4, mycomparison(true)); // 小顶堆
//cout << fifth.top() << endl; //输出最小元素10
return 0;
}