Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Priority queue of pairs in reverse order

I'm wanting to do something like this:

priority_queue< pair<int, int>, vector<int>, greater<int> > Q;

This works fine if the type I'm comparing is int, i.e.:

priority_queue< int, vector<int>, greater<int> > Q;

however, obviously with the pair<int, int>, there is no way of comparing the pairs in the queue with the standard >. I was wondering what I should do? How would I implement an overloaded > or is there another way I can create a priority queue of pairs with the smallest pair.second being at the top of the queue?

like image 812
bqui56 Avatar asked May 26 '12 10:05

bqui56


People also ask

How do I get my priority queue in reverse order?

In Java, Priority Queue, by default implement min Priority Queue, If we need to change the order of Priority Queue from min to max Priority Queue, then we use some methods as follows: Using default Comparator Collections. reverseOrder() Using custom Comparator.

How does priority queue work for pairs?

Priority queue is an abstract data type for storing a collection of prioritized elements that supports insertion and deletion of an element based upon their priorities, that is, the element with first priority can be removed at any time.

Is priority queue in ascending order?

It supports only those elements that are comparable. Hence, a priority queue in the data structure arranges the elements in either ascending or descending order. You can think of a priority queue as several patients waiting in line at a hospital.

Can we store pair in priority queue?

Yes, it's possible. std::priority_queue has a templated Compare functor that is used for sorting. You can use a lambda as the functor in c++11.


2 Answers

Have you tried this?

typedef pair<int, int> P;
priority_queue< P, vector<P>, greater<P> > Q;

This will give the reverse ordering of the normal operator< for pair<int, int>, which will start with the smallest first tie-broken with smallest second.

If you want to sort by smallest second first and first second (!) then you'll need a new sorting functor:

struct Order
{
    bool operator()(P const& a, P const& b) const
    {
        return a.second < b.second || a.second == b.second && a.first < b.first;
    }
}

Then use:

priority_queue< P, vector<P>, Order > Q;
like image 115
Peter Alexander Avatar answered Nov 15 '22 16:11

Peter Alexander


You should create your own domain class rather than using pair<int, int> here, as far as I can see. Then you can overload > as you like.

like image 28
Hakan Serce Avatar answered Nov 15 '22 17:11

Hakan Serce