stl priority queue based on lower value first

前端 未结 6 1857
故里飘歌
故里飘歌 2020-12-18 15:35

I have a problem with stl priority queue.I want to have the priority queue in the increasing order,which is decreasing by default.Is there any way to do this in priority qu

相关标签:
6条回答
  • 2020-12-18 16:17
    1. priority_queue has template parameters that specify the container type and the comparison to use for ordering. By default, the comparison is less<T>; to get the opposite ordering, use priority_queue<T, vector<T>, greater<T>>.

    2. Insertion into a priority queue takes logarithmic time, so building a queue of N items has complexity O(N logN), the same as building and sorting a vector. But once it's built, insertion into the priority queue is still logarithmic, while insertion into a sorted vector is linear.

    0 讨论(0)
  • 2020-12-18 16:17

    Use the type

    priority_queue<T, vector<T>, greater<T> >
    
    0 讨论(0)
  • 2020-12-18 16:29

    Replace T bellow with variable type. You will get your work done

    priority_queue<T, vector<T>, greater<T> > PQ;
    

    As example for int type variable you can write it like this:

    priority_queue<int, vector<int>, greater<int> > Q;
    
    0 讨论(0)
  • 2020-12-18 16:30

    Use a different comparator as the 3rd template argument of std::priority_queue.

    priority_queue is a container adaptor that works on any sequence you define. The performance of insertion is equal to the std::push_heap operation and takes logarithmic time. So the complexity to sorting after all insertions are done isn't equal. If you insert a fixed amount and work the queue afterwards a vector and a single sort could be more efficient.

    0 讨论(0)
  • 2020-12-18 16:33

    You can use comparator class/struct to achieve the same in priority queue.

    class CompareHeight 
    { 
        public:
            bool operator()(int &p1, int &p2) 
            {
                return p1 > p2; 
            } 
    };
    

    Now declare the priority queue as

    priority_queue<int, vector<int>, CompareHeight> pq;
    
    0 讨论(0)
  • 2020-12-18 16:39

    You can just push values multiplying them by -1 so it will be stored in reverse order unlike the actual default order...and multiply the value with -1 again while retrieving data to get it in its actual form.

    0 讨论(0)
提交回复
热议问题