zoukankan      html  css  js  c++  java
  • (priority_queque)优先队列容器适配器的使用

    容器适配器就是在基础的顺序容器上定义的一个新的接口。

    这里的顺序容器包括:vector,list,deque.

    priority_queque是建立在vector或deque容器上的。

    优先级队列和普通的队列操作一样。

    包括:出队,入队,读取队首元素,判断队列是否空等。

    只不过不同的是优先级队列并非先进先出,而是根据优先级出队,它会将队列中最大的元素出队。

    好像是对普通队列进行了从大到小排序后,在进行出队操作。

    队列中的元素比较规则默认是按元素的值由大到小排序。

    当然,也可以自己定义比较规则。

    如果优先队列的元素是类类型。可以重载"<"操作符,定义自己的比较规则。

    如下:

    #include <queue>

    #include <iostream>

    using namespace std;

    struct data

    {

           int id;

           bool operator<(const data& d) const

           {

                  return d.id<id;

           }

    };

    int main()

    {

           priority_queue<data> pd;

           data temp;

           temp.id = 2;

           pd.push(temp);

           temp.id = 3;

           pd.push(temp);

           while (!pd.empty())

           {

                  cout<<pd.top().id<<endl;

                  pd.pop();

           }

           return 0;

    }

    通过重新定义小于关系,改变队列出队顺序。

    如果不是类类型。可以通过重载"()"操作符的方式定义优先级。

    如下

    #include <queue>

    #include <iostream>

    using namespace std;

    struct mycmp{

           bool operator()(const int &a, const int &b)

           {

                  return a>b;

           }

    };

    int main()

    {

           priority_queue<int,vector<int>,mycmp> pq;

           pq.push(2);

           pq.push(3);

           while (!pq.empty())

           {

                  cout<<pq.top()<<endl;

                  pq.pop();

           }

           return 0;

    }

    优先级队列,我不常用,今天看到一个程序中使用,因此了解。

  • 相关阅读:
    总结一下最近用过的phpcms语法
    phpcms和php格式化时间戳
    为什么使用bootstrap在一个页面同时做两个轮播效果时,只有第一个有效??
    Jquery右击显示菜单事件,运用smartMenu插件。
    流程管理
    权限管理
    文件管理的练习(目录文件的打开,双击返回上一层目录、双击打开子目录文件)
    php部分--文件操作
    php部分--头像上传预览
    PHP部分--图片上传服务器、图片路径存入数据库,并读取
  • 原文地址:https://www.cnblogs.com/Open_Source/p/1904937.html
Copyright © 2011-2022 走看看