How can I create Min stl priority_queue?

前端 未结 9 858
误落风尘
误落风尘 2020-12-04 04:49

The default stl priority queue is a Max one (Top function returns the largest element).

Say, for simplicity, that it is a priority queue of int values.

相关标签:
9条回答
  • 2020-12-04 05:51

    In C++11 you could also create an alias for convenience:

    template<class T> using min_heap = priority_queue<T, std::vector<T>, std::greater<T>>;
    

    And use it like this:

    min_heap<int> my_heap;
    
    0 讨论(0)
  • 2020-12-04 05:51

    Multiply values with -1 and use max heap to get the effect of min heap

    0 讨论(0)
  • 2020-12-04 05:53

    Based on above all answers I created an example code for how to create priority queue. Note: It works C++11 and above compilers

    #include <iostream>
    #include <vector>
    #include <iomanip>
    #include <queue>
    
    using namespace std;
    
    // template for prirority Q
    template<class T> using min_heap = priority_queue<T, std::vector<T>, std::greater<T>>;
    template<class T> using max_heap = priority_queue<T, std::vector<T>>;
    
    const int RANGE = 1000;
    
    vector<int> get_sample_data(int size);
    
    int main(){
      int n;
      cout << "Enter number of elements N = " ; cin >> n;
      vector<int> dataset = get_sample_data(n);
    
      max_heap<int> max_pq;
      min_heap<int> min_pq;
    
      // Push data to Priority Queue
      for(int i: dataset){
        max_pq.push(i);
        min_pq.push(i);
      }
    
      while(!max_pq.empty() && !min_pq.empty()){
        cout << setw(10) << min_pq.top()<< " | " << max_pq.top() << endl;
        min_pq.pop();
        max_pq.pop();
      }
    
    }
    
    
    vector<int> get_sample_data(int size){
      srand(time(NULL));
      vector<int> dataset;
      for(int i=0; i<size; i++){
        dataset.push_back(rand()%RANGE);
      }
      return dataset;
    }
    

    Output of Above code

    Enter number of elements N = 4
    
            33 | 535
            49 | 411
           411 | 49
           535 | 33
    
    0 讨论(0)
提交回复
热议问题