浅谈优先队列(常用)

C++ STL 优先队列

优先队列特点:除了有与队列相同的先进先出的特点之外,优先队列还有自动排序的特点。

优先队列基本定义方式:

1、priority_queue<数据类型>队列名称,例:

2、priority_queue<结构体>队列名称,例:

该结构体中重载了<  方法

3、priority_queue<int,vector<>int ,greater(less)<int> >队列名称

优先队列常用方法:

优先队列实现:

1、priority_queue<数据类型>队列名称,例:

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

int main(){
	priority_queue<int>p;
	priority_queue<char>q;
	p.push(2);p.push(1);p.push(12);p.push(5);p.push(8);
	q.push('a');q.push('c');q.push('x');q.push('b');q.push('d');
	while(!p.empty()){
		printf("%d ",p.top()),p.pop();
	}
	printf("\n");
	while(!q.empty()){
		printf("%c ",q.top()),q.pop();
	}
	
	return 0;
} 

运行结果:默认从大到小降序排序

2、priority_queue<结构体>队列名称,例:

#include<cstdio>
#include<queue>
using namespace std;
struct node{
	int x;
	bool operator < (const node  & a)const{
		return x<a.x;
	}
}a; 

int main(){
	//node是结构体,重载 < 
	priority_queue<node>p1;
	a.x = 2;p1.push(a);
	a.x = 1;p1.push(a);
	a.x = 12;p1.push(a);
	a.x = 5;p1.push(a);
	a.x = 8;p1.push(a);
	while(!p1.empty())
		printf("%d ",p1.top()),p1.pop();
	
        return 0;
} 

 

运行结果:降序

 

3、greater<>与less<>,例:

#include<cstdio>
#include<queue>
using namespace std;
int main(){
	
	priority_queue<int,vector<int>,greater<int> >q1;//此处注意最右边的两个>要用空格隔开,>>是右移符 
	priority_queue<int,vector<int>,less<int> >q2;
	int a[] = {2,1,12,5,8};
	for(int i=0;i<5;i++)
		q1.push(a[i]),q2.push(a[i]);
	printf("greater<>:");
	while(!q1.empty())
		printf("%d ",q1.top()),q1.pop();
	printf("\nless<>:");
	while(!q2.empty())
		printf("%d ",q2.top()),q2.pop();
	return 0;
} 

 

运行结果:

 

总结:

优先队列默认排序为降序排序,

而greater<>与less<>分别升序(从小到大)和降序(从大到小)。

  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值