zoukankan      html  css  js  c++  java
  • C++ 优先级队列 priority_queue

    优先级队列(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

    
    
  • 相关阅读:
    界面和效果
    第一篇博客
    Java作业(六)
    Java学习(五)
    Java学习(四)
    JAVA学习(三)
    Java学习(二)
    Java学习心得
    音乐播放器项目计划进度安排
    课程设计 高云鹏 郑帅康 张程 姬泽辉
  • 原文地址:https://www.cnblogs.com/patrolli/p/11235123.html
Copyright © 2011-2022 走看看