首页 > 编程语言 > 详细

C++ 优先级队列 priority_queue

时间:2019-07-24 00:11:25      阅读:81      评论:0      收藏:0      [点我收藏+]

优先级队列(priority_queue)是一种容器适配器(container adaptor)。它要求容器具有front、push_back、pop_back等操作,并且容器具有随机访问的能力,故优先队列可以基于vector或者deque构造。

queue和prioruty_queue都被定义在queue头文件中。

几种定义形式:

using namespace std;
int myint[4] = {10, 60, 50, 20};
priority_queue<int> first;  //创建一个空的优先队列
priority_queue<int> second(myint, myint+4); //second包含四个int,其中60在队列的顶部(默认是越小的优先级越低,所以最大的60在top
priority_queue<int, vector<int>, greater<int> > third(myint, myint+4); //third同样包含四个int,但是它的优先级是越大优先级越低,所以最小的10在top

  

也可以自定义比较优先级,其操作为:

//定义比较的类或结构体,并重载()运算符
class mycmp
{
  bool reverse;
public:
  mycmp(const bool& revparam=false){reverse = revparam;}
  bool operator()(const int& lhs, const int& rhs) const
  {
    if(reverse) return (lhs > rhs);
    else return (lhs < rhs);
}
//使用自己定义的比较优先级
typedef priority_queue<int, vector<int>, mycmp> mypq_type;
mypq_type fourth;
mypq_type fifth(mycmp(true));

  

成员函数有:

empty  Test whether container is empty
size  Return size
top  Access top element
push  Insert element 
emplace   Construct and insert element
pop  Remove top element
swap   Swap contents

 

 再添加一个博客链接,讲得比较详细:https://blog.csdn.net/c20182030/article/details/70757660

C++ 优先级队列 priority_queue

原文:https://www.cnblogs.com/patrolli/p/11235123.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!