优先队列使用方法

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

于是弄了个优先队列水过

干脆总结下


头文件:#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为第二级排序。升序还是降序呢?

大家自己去做试验吧!

全部评论

相关推荐

10-09 17:17
已编辑
门头沟学院 Java
活泼的代码渣渣在泡池...:同学你好,我也是学院本,后天要面这个亚信科技,是实习,请问问题都啥样呀,我项目就做了网上的,这是第一次面试
投递多益网络等公司10个岗位
点赞 评论 收藏
分享
09-14 17:23
门头沟学院
故事和酒66:所以说副业很重要,程序员干到40岁,再怎么也赚300万了,吃吃利息也够活下去
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务