c++-STL-priority_queue(优先队列)

如果我们在竞赛中如果用堆来实现一个优先队列,代码量不说,还有可能出现低级错误。这时候,c++ STL就是我们比赛中的一个好助手了。
和其他STL容器一样,priority_queue一样的又插入和删除元素。顾名思义,priority_queue就是权值大的优先出列,我们只需要插入数据,并拟定规则(重载操作符),priority_queue 自动排序(还是利用大顶堆,原理在此不详述)。
priority_queue 的构造函数有七种,这里只讲述比较重要的
priority_queue<int> que;
priority_queue<int,list<int>> (复制构造函数)
priority_queue<int,vector<int>,cmp>(cmp为比较函数)
常用的方法有:
[table]
|c.top()| 返回队列头部数据
|c.push(elem)| 在队列尾部增加elem数据
|c.pop()| 队列头部数据出队
|c.empty()| 判断队列是否为空
|c.size() |返回队列中数据的个数
[/table]

但我们要将自己定义的类型使用priority_queue怎么办,重载运算符,代码如下:

[/code]
#include<iostream>
#include<queue>
using namespace std;
struct node{
int x;
int y;
friend bool operator < (const node a,const node b){
if(a.x!=b.x){
return b.x<a.x;
}else{
return b.y<a.y;
}
//x小的先出列,相同再根据 y 的大小
}
};
int main(){
priority_queue<node> que;
node nodeList[6];
for(int i=1;i<6;i++){
node newNode;
newNode.x = i;
newNode.y = i;
que.push(newNode);
}
node newNode;
newNode.x = 3; newNode.y=4;
que.push(newNode);
while(!que.empty()){
node node1 = que.top();
que.pop();
cout << node1.x << " " << node1.y << endl;
}
system("pause");
return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值