Priority queues are a type of container adapters, specifically designed such that the first element of the queue is either the greatest or the smallest of all elements in the queue and elements are in nonincreasing order (hence we can see that each element of the queue has a priority {fixed order}).
优先队列是一种容器适配器,特别是用来指定第一个队列元素是所有元素中最大或者最小的,且元素是non-increasing order(如果连续元素小于或等于序列中的前一元素)的顺序。
However in C++ STL, by default, the top element is always the greatest element. We can also change it to the smallest element at the top. Priority queues are built on the top to the max heap and use array or vector as an internal structure.
然而,在c++中,默认最上方的元素一直是最大的。我们也能改变它为最小的。优先队列建立在大顶堆(top to the max heap,堆的顶部是最大值)并使用array 或者vector作为内部结构。
How to create a min-heap for the priority queue?
We can pass another parameter while creating the priority queue to make it a min heap. C++ provides the below syntax for the same.
Syntax:
priority_queue <int, vector<int>, greater<int>> g = gq;
模板声明带有三个参数,priority_queue<Type, Container, Functional>
Type 为数据类型, Container 为保存数据的容器, Functional 为元素比较方式。
Container 必须是用数组实现的容器,比如 vector, 但不能用list.
STL里面默认用的是vector. 比较方式默认用operator<
// C++ program to demonstrate min heap for priority queue
#include <iostream>
#include <queue>
using namespace std;
void showpq(
priority_queue<int, vector<int>, greater<int> > gq)
{
priority_queue<int, vector<int>, greater<int> > g = gq;
while (!g.empty()) {
cout << '\t' << g.top();
g.pop();
}
cout << '\n';
}
// Driver Code
int main()
{
priority_queue<int, vector<int>, greater<int> > gquiz;
gquiz.push(10);
gquiz.push(30);
gquiz.push(20);
gquiz.push(5);
gquiz.push(1);
cout << "The priority queue gquiz is : ";
showpq(gquiz);
cout << "\ngquiz.size() : " << gquiz.size();
cout << "\ngquiz.top() : " << gquiz.top();
cout << "\ngquiz.pop() : ";
gquiz.pop();
showpq(gquiz);
return 0;
}