C++ STL库优先队列(priority_queue)的使用

//priority_queue的使用
#include<bits/stdc++.h>
using namespace std;
int main()
{
	priority_queue<int> pq;//大顶堆 
	//可定义priority_queue<Type, Container, Functional>
	//Type是数据类型,Container是容器类型(vector,deque,map)不能用list默认为vector
	//Functional是比较的方法,默认降序(大根堆) 
	//升序:priority_queue<int,vector<int>,greater<int> > q;
	for(int i = 1;i < 5;i++)
	{
		pq.push(i);//queue.push(n);插入一个元素到队尾并排序 
	}
	cout<<pq.size()<<endl;//queue.size();返回队列元素个数 
	while(!pq.empty())//queue.empty();若队列为空返回true 
	{
		cout<<pq.top()<<' '; //访问队头元素 
		pq.pop(); //弹出队头元素 (不返回值) 
	}
	cout<<endl;
	priority_queue< pair<int,int> > a; //pair捆绑两个元素,pair<Type,Type>第一个为key,第二个为value 
	pair<int,int> para1(1,2);//可以通过para1.first访问key,para1.second访问value 
	pair<int,int> para2(1,3);
	pair<int,int> para3(2,3);
	a.push(para1);
	a.push(para2);
	a.push(para3);//先比较key大小,大的往前排,再比较value大小 
	while(!a.empty())
	{
		cout<<a.top().first<<' '<<a.top().second<<endl;
		a.pop();
	}
	return 0;
} 
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 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、付费专栏及课程。

余额充值