zoukankan      html  css  js  c++  java
  • 优先队列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;

  • 相关阅读:
    ExtJs学习准备工作(二) firebug firefox插件的安装 全新时代
    Hibernate系统中调试SQL方式 全新时代
    Eclipse工程出现红叉导致无法编译的问题 全新时代
    javascript 取table中内容
    Asp.Net中清空所有textbox的几种方法
    SQL Server:使用系统存储过程实现的通用分页存储过程
    C# 检查网络是否连通
    sq分页原理
    SQL Server:日志备份和差异备份还原中的常见问题示例
    javascript:连接数据库
  • 原文地址:https://www.cnblogs.com/hailong88/p/3237206.html
Copyright © 2011-2022 走看看