priority_queue的用法

priority_queue本质是一个堆。

1、priority_queue说明

头文件:#include<queue>

函数原型
priority_queue<Type, Container, Functional>

其中Type 为数据类型,Container为保存数据的容器,Functional 为元素比较方式。Container必须是用数组实现的容器,比如vector,deque等等,但不能用 list。STL里面默认用的是vector。

2、priority_queue中元素的比较

用法一
优先队列的第一种用法,也是最常用的用法:
priority_queue<int> q;

比较方式默认用operator<操作符操作,所以如果把后面2个参数缺省的话,优先队列就是大顶堆(降序),队头元素最大。

以下代码返回一个降序输出:

#include <iostream>
#include <queue>
using namespace std;

int main()
{
	priority_queue<int> q;
	int a[] = {10,8,1,6,3,5,2,9,4,7};
	int len = sizeof(a) / sizeof(a[0]);
	for (int i = 0; i< len; i++)
		q.push(a[i]);
	while (!q.empty())
	{
		cout << q.top() << " ";
		q.pop();
	}
	cout << endl;
	return 0;
}

在这里插入图片描述

用法二
如果要用到小顶堆,则一般要把模板的三个参数都带进去。STL里面定义了一个仿函数 greater<>,对于基本类型可以用这个仿函数声明小顶堆。需要添加头文件#include<functional>

#include <iostream>
#include <queue>
#include <functional> // std::greater
using namespace std;

int main()
{
	priority_queue<int, vector<int>, greater<int> > q;
	int a[] = {10,8,1,6,3,5,2,9,4,7};
	int len = sizeof(a) / sizeof(a[0]);
	for (int i = 0; i< len; i++)
		q.push(a[i]);
	while (!q.empty())
	{
		cout << q.top() << " ";
		q.pop();
	}
	cout << endl;
	return 0;
}

在这里插入图片描述
用法三
自定义优先级。

#include<iostream>
#include<queue>
using namespace std;

struct node
{
	friend bool operator< (node n1, node n2)
	{
		return n1.priority < n2.priority;
	}
	int priority;
	int value;
};

int main()
{	priority_queue<node> q;
	const int len = 5;
	node b[len];
	b[0].priority = 6; b[0].value = 1;
	b[1].priority = 9; b[1].value = 5;
	b[2].priority = 2; b[2].value = 3;
	b[3].priority = 8; b[3].value = 2;
	b[4].priority = 1; b[4].value = 4;

	for (int i = 0; i < len; i++)
		q.push(b[i]);
	cout << "优先级" << '\t' << "值" << endl;
	for (int i = 0; i < len; i++)
	{
		cout << q.top().priority << '\t' << q.top().value << endl;
		q.pop();
	}
	return 0;
}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值