简体   繁体   中英

stl priority queue based on lower value first

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 queue.

And what is the complexity of building stl priority queue.If i use quick sort in an array which takes O(nlgn) is its complexity is similar to using priority queue???

Plz someone ans.Advanced thanx.

  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.

使用类型

priority_queue<T, vector<T>, greater<T> >

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.

您只需将值乘以-1就可以将其乘以-1,这样它将以与实际默认顺序不同的相反顺序存储...并在检索数据以使其实际形式时再次将值乘以-1。

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;

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM