3

Suppose we have a priority queue such as:

priority_queue<pair<int, int> > pQ; 

and we want pQ to be ordered so that the pair with the smallest second element is always first. Is there a simple way to accomplish this using C++11? It would be ideal if I had an elegant solution such as one that uses lambda functions. Is this possible?

3 Answers 3

4

You need to instantiate it with a custom comparison function, for example (namespace std assumed):

auto cmp = [](const pair<int, int>& lhs, const pair<int, int>& rhs) { return lhs.second < rhs.second; }; priority_queue<pair<int, int>, vector<pair<int, int>>, decltype(cmp)> pQ(cmp); 
Sign up to request clarification or add additional context in comments.

5 Comments

Can you describe how to use this?
@BobJonas Ehm, just use it?
How do I push things onto the queue?
@BobJonas Just like you normally would.
Oh. I was using the un-edited version before and it wasn't compiling. Thanks for this!
0

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.

Comments

0

auto cmp=[](pair a,pair b){return a.second>b.second;}; priority_queue,vector>,decltype(cmp)> pq(cmp);

this is min heap of pairs by the second element in the pair.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.