STL 优先队列

优先队列

优先队列(priorityqueue)普通的队列是一种先进先出的数据结构,元素在队列尾追加,而从队列头删除。在优先队列中,元素被赋予优先级。当访问元素时,具有最高优先级的元素最先删除。优先队列具有最高级先出(largest-in,first-out)的行为特征。

对于优先对列,在这里谈谈对结构体和一般情况的自定义优先级;

1.结构体

第一步 声明一个结构体

struct node{
	int x,y;
	int step;
	friend bool operator <(node a,node b)
	{
		a.step>b.step;         //定义从小到达排列
	}
};

第二步 声明队列

priority_queue<node> s;	

例子如下:

# include<stdio.h>
# include<queue>
# include<algorithm>
using namespace std;
struct node{
	int step;
	friend bool operator <(node a,node b)
	{
		return a.step>b.step;
	}
}a;
int main(){	
priority_queue<node> s;	
for(int i=10,j=1;i>=1;i--,j++)	
	{   a.step=i;
		s.push(a);
	}
while(!s.empty())	
	{
		printf("%d ",s.top().step);
		s.pop();
	}	
	return 0;
}

2.普通的

第一步 声明比较函数

struct cmp{
bool operator() (int& a,int& b)
	{  
		return a>b;
	}	
};

第二步 声明队列
priority_queue<int ,vector<int >,cmp> s;

例子如下:

# include<stdio.h>
# include<queue>
# include<algorithm>
using namespace std;
struct cmp{
bool operator() (int& a,int& b)
	{  
		return a>b;
	}	
};
int main(){	
priority_queue<int ,vector<int >,cmp> s;	
for(int i=10,j=1;i>=1;i--,j++)	
	{  
		s.push(i);
	}
while(!s.empty())	
	{
		printf("%d ",s.top());
		s.pop();
	}	
	return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值