Priority Queue in C++ STL优先队列

本文介绍了C++标准模板库(STL)中的优先队列,它默认实现为大顶堆,即顶部元素总是最大。通过传递额外参数,可以创建一个最小堆。示例代码展示了如何创建和操作一个最小堆的优先队列,包括插入元素、显示队列内容、获取顶部元素和弹出顶部元素等操作。
摘要由CSDN通过智能技术生成

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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值