• 优先队列


    优先队列

    c++ STL 中 优先队列用法(默认为less,最大堆),头文件为需要包括 :

    #include <queue>
    /*
    *  std::priority_queue:
    *  template <class T, class Container = vector<T>,
    *  class Compare = less<typename Container::value_type> > class *  priority_queue;
    */

    例子:

    int a[7] = {1,4,5,2,8,3,0};
    priority_queue <int, vector<int>, less<int> > p;
    priority_queue <int, vector<int>, greater<int> >q;
    for(int i = 0; i < 5; i++)
        {
            p.push(a[i]);
            q.push(a[i]);
        }
    //output p:8 5 4 2 1
    //output q:1 2 4 5 8

    2. greater的用法:

    // greater example
    #include <iostream>     // std::cout
    #include <functional>   // std::greater
    #include <algorithm>    // std::sort
    
    int main () {
      int numbers[]={20,40,50,10,30};
      std::sort (numbers, numbers+5, std::greater<int>());
      for (int i=0; i<5; i++)
        std::cout << numbers[i] << ' ';
      std::cout << '
    ';
      return 0;
    }
    /************output: 50 40 30 20 10 *************/

     3. 在优先队列中使用greater: 却是从小到大排列顺序。

    #include <queue>
    #include <iostream>
    #include <vector>
    #include <algorithm>
    using namespace std;
    
    class cmp
    {
        bool reverse;
    public:
        cmp(const bool &re = false)
        {    
            reverse = re;
        } 
    
        bool operator() (int &a, int &b) const
        {
            if(reverse) return (a > b);
            else return (a < b);
        }
    };
    
    int main()
    {
        int myints[] = {10, 60, 50, 20};
        //默认从大到小 默认为less 
        priority_queue<int> second (myints, myints+4); //60, 50, 20, 10
        while(!second.empty())
        {
            cout << " " << second.top();
            second.pop();
        }
        cout << endl;
        /*从小到大: 10, 20, 50, 60*/
        priority_queue<int, vector<int>, greater<int> > third (myints, myints + 4);
        
        while(!third.empty())
        {
            cout << " " << third.top();
            third.pop();
        }
        cout << endl;
        /*从小到大, 10 ,20, 50, 60*/
        priority_queue<int, vector<int>, cmp> fourth(myints, myints+4, cmp(true));
        
        while(!fourth.empty())
        {
            cout << " " << fourth.top();
            fourth.pop();
        }
        cout << endl;
    
        return 0;
    }
    The Safest Way to Get what you Want is to Try and Deserve What you Want.
  • 相关阅读:
    c#同类型操作最终得到的结果将是同类型
    RabbitMQ的高级特性(五)延迟队列 lq
    RabbitMQ的高级特性(二)消费端限流 lq
    RabbitMQ的高级特性(一)可靠性传递 lq
    RabbitMQ的高级特性(四)死信队列 lq
    RabbitMQ的高级特性(三)TTL lq
    rabbitmq的常见问题及解决方案 lq
    RabbitMQ集群搭建 lq
    炫酷设计
    【转】全球超酷智能眼镜扫描
  • 原文地址:https://www.cnblogs.com/Shinered/p/9016897.html
Copyright © 2020-2023  润新知