• 优先队列priority_queue


    优先队列容器与队列一样,只能从队尾插入元素,从队首删除元素。但是它有一个特性,就是队列中最大的元素总是位于队首,所以出队时,并非按照先进先出的原则进行,而是将当前队列中最大的元素出队。这点类似于给队列里的元素进行了由大互小的顺序排序。元素的比较规则默认按元素值由大到小排序,可以重载“<”操作符来重新定义比较规则。  使用优先队列时也需要声明头文件

    #include <queue>

    #include <iostream>

    #include <queue>

    using namespace std;

    int main() {     

        priority_queue<float> q;    

         // insert three elements into the priority queue    

      q.push(66.6);

         q.push(22.2);

         q.push(44.4);    

        // read and print two elements    

      cout << q.top() << ' ';    

      q.pop();     

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

         q.pop();     

     // insert three more elements

         q.push(11.1); 

        q.push(55.5);    

      q.push(33.3);     

     // skip one element 

        q.pop(); 

         // pop and print remaining elements 

        while (!q.empty()) {         

          cout << q.top() << ' ';

                q.pop(); 

        }     

    cout << endl;

    }  

    如果优先队列的元素类型是结构体,可以通过在结构体中重载“<“操作符的方法来修改优先队列的优先性。

           #include <queue>

         #include <string>

           #include <iostream>

       using namespace std;

         //定义结构体

        struct info {

          string name; 

         float score; 

         bool operator < (const info &a) const  {

                   //按照score由小到大进行排列,如果要使用由大到小,使用“>”即可   return a.score<score; 

         }

      }; 

      int main()

      { 

        priority_queue <info> pq;  info in; 

         in.name="Jack";

          in.score=68.5; 

         pq.push(in);  

         in.name="Bomi";

          in.score=18.5; 

         pq.push(in);  

         in.name="Peti"; 

         in.score=90; 

         pq.push(in);  

         while(!pq.empty()) 

         {  

            cout<<pq.top().name<<": "<<pq.top().score<<endl; 

             pq.pop(); 

         } 

       return 0;

  • 相关阅读:
    bzoj1066: [SCOI2007]蜥蜴
    bzoj3504: [Cqoi2014]危桥
    bzoj2756: [SCOI2012]奇怪的游戏
    bzoj1570: [JSOI2008]Blue Mary的旅行
    Ultra-QuickSort
    Bin Packing
    Watering Grass
    区间覆盖
    抄书 Copying Books UVa 714
    分馅饼 Pie
  • 原文地址:https://www.cnblogs.com/hailong88/p/3237206.html
Copyright © 2020-2023  润新知