优先级队列

        普通的队列是一种先进先出的结构,即元素插入在队尾,元素删除在队头。但是在优先级队列中,元素被赋予了优先级,当插入元素时,同样是在队尾,但是元素会按照优先级进行位置调整。优先级越高,调整后的元素位置越靠近队头;同样的,删除元素也是按招优先级进行,优先级最高的元素(队头)最先被删除。其实可以认为,优先级队列就是堆实现的一种数据结构。

创建priority_queue(初阶)

        优先级队列的创建有很多种——简单内置类型的大根堆或小根堆、存储字符串的大根堆或小根堆、存储自定义类型的大根堆或小根堆。在初阶阶段,先用简单的int类型建堆,重点学习priority_queue的用法。(注意:priority_queue包含在<queue>这个头文件中

size & empty

        size返回元素个数,empty返回优先级队列是否为空

push

        往优先级队列中添加一个元素

pop

        删除优先级最高的元素

top

        获取优先级最高的元素

所有代码测试

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

int a[10] = {1, 41, 23, 10, 11, 2, -1, 99, 14, 0};

int main()
{
	priority_queue<int> heap; //默认是一个大根堆
	
	for(auto e : a)
	{
		heap.push(e);
	}
	
	while(heap.size())
	{
		cout << heap.top() << " ";
		heap.pop();
	}
	
	return 0;
}

创建priority_queue(进阶)

内置类型

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

int a[10] = {1, 41, 23, 10, 11, 2, -1, 99, 14, 0};

int main()
{
	//大根堆
	priority_queue<int> heap1; // 默认是一个大根堆
	
	priority_queue<int, vector<int>, less<int>> heap2; // 也是大根堆
	
	//小根堆
	priority_queue<int, vector<int>, greater<int>> heap3; // 小根堆
	
	for(auto e : a)
	{
		heap1.push(e);
		heap2.push(e);
		heap3.push(e);
	}
	
	while(heap1.size())
	{
		cout << heap1.top() << " ";
		heap1.pop();
	}
	cout << endl;
	
	while(heap2.size())
	{
		cout << heap2.top() << " ";
		heap2.pop();
	}
	cout << endl;
	
	while(heap3.size())
	{
		cout << heap3.top() << " ";
		heap3.pop();
	}
	
	return 0;
}

结构体类型

        当优先级队列里面存的是结构体类型时,需要在结构体中重载比较运算符,从而创建出大根堆或者小根堆。

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

struct node
{
	int a, b, c;

	//重载 < 运算符
	//以b为基准创建大根堆
	bool operator < (const node& x) const
	{
		return b < x.b;
	}

	////以b为基准创建小根堆
	//bool operator < (const node& x) const
	//{
	//	return b > x.b;
	//}
};

int main()
{
	priority_queue<node> heap;

	for (int i = 1;i <= 5;i++)
	{
		heap.push({ i,i + 1,i + 2 });
	}

	while (!heap.empty())
	{
		node t = heap.top();
		heap.pop();
		cout << t.a << " " << t.b << " " << t.c;
	}

	return 0;
}

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐