优先队列使用方法

前几天做哈夫曼的贪心,想自己模拟搞就是写不对

于是弄了个优先队列水过

干脆总结下


头文件:#include<queue>


一:使用的函数

 成员函数:

empty

true if the priority queue has no elements

pop

removes the top element of a priority queue

push

adds an element to the end of the priority queue

size

returns the number of items in the priority queue

top

returns the top element of the priority queue

常用的也是这么几个

使用方法:

判断是否为空:


if (q.empty()) ...
 


弹出元素:


q.pop();


插入元素:


q.push(x);
 

其中x必须是q所申明的优先队列的元素类型


清除原队列(尤其是多组数据的时候记得注意):


while(!q.empty()) q.pop();



二:从大到小排序


priority_queue<int> q;


其中<int>是变量的类型,可以任意类型。

q是queue队列名称


三:从小到大排序


priority_queue<int,vector<int>,greater<int> > q;




四:自定义排序

多级变量排序的时候需要自定义结构体变量

struct node{

      int x,y;

      friend bool operator < (node n1,node n2){

           if (n1.x!=n2.x) return n1.x<n1.x;

           return n1.y<n2.y;

    }

}

priority_queue<node> q;




从上面的小于号的重载可以看得出来,node中是以x为第一级排序,以y为第二级排序。升序还是降序呢?

大家自己去做试验吧!

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值