C++ STL priority_queue优先队列的使用方法

一、基本概念

priority_queue是优先队列,就像普通队列一样,只是队列中的第一个元素是队列中所有元素中最大的,算是C ++中的堆的一种实现,priority_queue默认是最大堆。元素可以任意的顺序插入,插入的时间复杂度为O(logn)

创建int类型的优先级队列的语法:

priority_queue <int> pq;

二、成员方法

  • push函数:在priority_queue中插入一个元素,时间复杂度为O(logn)
  • pop函数:从priority_queue中删除最上面的元素(最大元素),并将优先级队列的大小减小1。
  • top函数:返回在priority_queue顶部的元素,该元素是队列中存在的最大元素。
  • size函数:返回priority_queue的元素个数。
  • empty函数:返回truefalse,如果priority_queue为空,则返回true,否则返回false
  • swap函数:交换两个priority_queue的值。
#include <iostream> 
#include <queue> 

using namespace std;

void showpq(priority_queue <int> pq)
{
	while (!pq.empty())
	{
		cout << ' ' << pq.top();
		pq.pop();
	}
	cout << '\n';
}

int main()
{
	priority_queue <int> pq1;
	pq1.push(10); // inserts 10 to pq1 , now top = 10
	pq1.push(30); // inserts 30 to pq1 , now top = 30
	pq1.push(20); // inserts 20 to pq1 , now top = 30
	pq1.push(50); // inserts 50 to pq1 , now top = 50
	pq1.push(90); // inserts 90 to pq1 , now top = 90

	cout << "The priority_queue pq1 is:";
	showpq(pq1);

	cout << "\npq1.size():" << pq1.size();
	cout << "\npq1.top():" << pq1.top();


	cout << "\npq1.pop()\n";
	pq1.pop(); // remove 90 to pq1 , now top = 50
	cout << "The priority_queue pq1 is:";
	showpq(pq1);

	priority_queue <int> pq2;
	pq2.push(3);
	pq2.push(5);
	pq2.push(7);
	pq2.push(9);
	cout << "The priority_queue pq2 is:";
	showpq(pq2);

	pq1.swap(pq2);
	cout << "after swap:" << endl;
	cout << "The priority_queue pq1 is:";
	showpq(pq1);
	cout << "The priority_queue pq2 is:";
	showpq(pq2);

	system("pause");
	return 0;
}

运行结果:

The priority_queue pq1 is: 90 50 30 20 10

pq1.size():5
pq1.top():90
pq1.pop()
The priority_queue pq1 is: 50 30 20 10
The priority_queue pq2 is: 9 7 5 3
after swap:
The priority_queue pq1 is: 9 7 5 3
The priority_queue pq2 is: 50 30 20 10
请按任意键继续. . .

三、如何创建最小堆?

语法:

priority_queue<int, vector<int>, greater<int> > pq;

其中,greaterSTL内建的关系运算类函数对象(也就是仿函数),并且是一个二元运算符。

template<class T> bool greater<T> //大于
#include <iostream>
#include <queue>

using namespace std;

template<typename T> void print_queue(T& q) {
	while (!q.empty()) {
		cout << q.top() << " ";
		q.pop();
	}
	cout << '\n';
}
void showpq(priority_queue <int> pq)
{
	while (!pq.empty())
	{
		cout << ' ' << pq.top();
		pq.pop();
	}
	cout << '\n';
}
int main() {
	priority_queue<int> pq1; // 最大堆

	for (int n : {1, 8, 5, 6, 3, 4, 0, 9, 7, 2})
		pq1.push(n);

	print_queue(pq1);

	priority_queue<int, vector<int>, greater<int> > pq2; // 最小堆

	for (int n : {1, 8, 5, 6, 3, 4, 0, 9, 7, 2})
		pq2.push(n);

	print_queue(pq2);

	system("pause");
	return 0;
}

运行结果:

9 8 7 6 5 4 3 2 1 0
0 1 2 3 4 5 6 7 8 9
请按任意键继续. . .

四、自定义数据类型的优先队列用法

前面都是用的int类型的优先队列,如果是自定义数据类型,比如结构体,那么怎么使用优先队列呢?

有一个Person结构体,含有两个变量AgeHeight,定义如下:

struct Person{ 
    int Age; 
    float Height; 
} 

在定义优先队列的时候,priority_queue<Person> pq;,程序并不知道该如何对Person这种数据类型排序,就会报错。这时就需要运算符重载或者写仿函数来定义优先级,使得优先队列知道如何存储数据。对于自定义Person类型。

  • 运算符重载的方式
#include <iostream> 
#include <queue> 
using namespace std;
#define ROW 5 
#define COL 2 

struct Person {
	int age;
	float height;

	// 初始化结构体变量
	Person(int age, float height)
		: age(age), height(height)
	{
	}
};
// 重载 operator<
bool operator<(const Person& p1, const Person& p2) {
	return p1.height < p2.height;
}

int main()
{
	priority_queue<Person> pq;

	float arr[ROW][COL] = { { 30, 5.5 }, { 25, 5 },
					{ 20, 6 }, { 33, 6.1 }, { 23, 5.6 } };

	for (int i = 0; i < ROW; ++i) {
		// 使用Person的构造函数生成的临时变量,压到优先队列pq中
		pq.push(Person(arr[i][0], arr[i][1]));
	}

	while (!pq.empty()) {
		Person p = pq.top();
		pq.pop();
		cout << p.age << " " << p.height << "\n";
	}
	system("pause");
	return 0;
}
  • 仿函数的方式
#include <iostream> 
#include <queue> 
using namespace std;
#define ROW 5 
#define COL 2 

struct Person {
	int age;
	float height;

	// 初始化结构体变量
	Person(int age, float height)
		: age(age), height(height)
	{
	}
};

// 仿函数,里面实现了Person类型的()运算符重载函数
struct CompareHeight {
	bool operator()(Person const& p1, Person const& p2)
	{
		return p1.height < p2.height; // 升序
	}
};

int main()
{
	priority_queue<Person, vector<Person>, CompareHeight> pq;
 
	float arr[ROW][COL] = { { 30, 5.5 }, { 25, 5 },
					{ 20, 6 }, { 33, 6.1 }, { 23, 5.6 } };

	for (int i = 0; i < ROW; ++i) {
		// 使用Person的构造函数生成的临时变量,压到优先队列pq中
		pq.push(Person(arr[i][0], arr[i][1]));
	}

	while (!pq.empty()) {
		Person p = pq.top();
		pq.pop();
		cout << p.age << " " << p.height << "\n";
	}
	system("pause");
	return 0;
}

运行结果:

33 6.1
20 6
23 5.6
30 5.5
25 5
请按任意键继续. . .

五、参考文章

https://www.geeksforgeeks.org/priority-queue-in-cpp-stl/

https://en.cppreference.com/w/cpp/container/priority_queue

https://www.geeksforgeeks.org/stl-priority-queue-for-structure-or-class/

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C++ STL中的priority_queue是一个优先队列,它是一个使用堆来实现的容器。它可以按照一定的优先级顺序存储元素,并且每次访问队首元素都是访问优先级最高的元素。 在使用priority_queue时,可以通过定义不同的比较函数来指定元素的优先级顺序。默认情况下,对于基本类型,默认是大顶堆,降序队列。也可以通过指定参数来实现小顶堆,升序队列。例如: priority_queue<int, vector<int>, greater<int>> q; //小顶堆,升序队列 priority_queue<int, vector<int>, less<int>> q; //大顶堆,降序队列 在对priority_queue进行操作时,可以使用push()函数向队列中插入元素,使用top()函数获取队首元素,使用pop()函数删除队首元素。 在自定义类型的优先队列中,可以重载运算符>或<来定义优先级。例如,可以重载operator>来定义小顶堆,即优先级较小的元素排在前面。示例代码如下: struct Node{ int x, y; Node(int a=0, int b=0): x(a), y(b) {} }; bool operator> (Node a, Node b){ if(a.x == b.x) return a.y > b.y; return a.x > b.x; } priority_queue<Node, vector<Node>, greater<Node>> q; q.push(Node(rand(), rand())); while(!q.empty()){ cout<<q.top().x<<' '<<q.top().y<<endl; q.pop(); } 总结来说,C++ STL中的priority_queue是一个使用堆实现的优先队列,可以按照指定的优先级顺序存储元素。可以通过定义不同的比较函数或重载运算符来指定优先级规则。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [【总结】C++ 基础数据结构 —— STL优先队列priority_queue) 用法详解](https://blog.csdn.net/weixin_44668898/article/details/102132580)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值