优先队列 C++

8 篇文章 11 订阅

1.头文件:include<queue>

2.定义:优先队列和队列一样,只能从队尾插入元素,从队首删除元素。队列中最大的元素总是位于队首。可以通过重载<运算符来重新定义比较规则。

3.优点:自动排序

4.声明:priority_queue<数据类型> 队列名;

5.常用的声明:

5.1基本常量的优先队列:

priority_queue<int> q1;
priority_queue<double> q2;

5.2常用的优先队列:

priority_queue <int,vector<int> ,greater<int> > q;//使元素按照从小到大顺序出队 
priority_queue <int,vector<int> ,less<int> > q2;//降序排列 ,无需声明vector头文件
5.3自定义结构体优先队列
#include<iostream>
#include<queue> 
using namespace std;
struct Node{
	int id;
	int x;
}; 
bool operator < (const Node &a,const Node &b){
		return a.id<b.id;
}
int main()
{
	priority_queue<Node> q;
	return 0;
}

6.常用操作:

empty()    如果队列为空,则返回真

pop()    删除队列第一个元素

push()    加入一个元素

size()    返回队列的元素个数

top()    取队顶元素

7.测试代码:

#include<iostream>
#include<queue> 
using namespace std;
struct Node{
	int id;
	int x;
	Node (int id,int x):id(id),x(x){}
	void print(){
		cout << id << " " << x << endl;
	}
}; 
bool operator < (const Node &a,const Node &b){
		return a.id < b.id;
}
int main()
{
	priority_queue<Node> q;
	int id,x;
	do{
		cin >> id >> x;
		q.push(Node(id,x));
	}while(id != 0);
	while(!q.empty()){
		Node a = q.top();
		q.pop();
		a.print();
	}
	return 0;
}


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

迷亭1213

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值