优先队列

本文介绍了C++中的优先队列,包括其基本操作如访问队头元素、判断队列是否为空、获取元素数量、插入和弹出元素。此外,还详细说明了如何通过priority_queue结构体自定义比较方式来实现优先级排序。
摘要由CSDN通过智能技术生成

头文件
基本操作和普通队列一样
top 访问队头元素
empty 队列是否为空
size 返回队列内元素个数
push 插入元素到队尾 (并排序)
pop 弹出队头元素
swap 交换内容

定义方式
priority_queue<type,container,方式>

int main()
{
	int n[6] = { 2,2,1,5,6,5,};
	priority_queue<int, vector<int>, greater<int>> a;//大根堆从小到大排序,不去重
	priority_queue<int, vector<int>, less<int>> b;//从大到小
	for (int i = 0; i < 6; i++) a.push(n[i]);
	for (int i = 0; i < 6; i++) b.push(n[i]);
	while (!a.empty())
	{
		cout << a.top() << " ";
		a.pop();
	}
	cout << endl;
	while (!b.empty())
	{
		cout << b.top() << " ";
		b.pop();
	}
}

结构体的自定义比较

struct node
{
	int x, y;
};
struct cmp1//自定义比较
{
	bool operator()(const node &a, const node &b) const
	{
		return a.x < b.x;//若x小那么结构体就小
	}
};
struct cmp2
{
	bool operator()(const node &a, const node &
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值