views:

172

answers:

2

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.

+6  A: 

Use std::greater as the comparison function:

std::priority_queue<int, std::vector<int>, std::greater<int> > my_min_heap;
James McNellis
+1 You got it first ;)
AraK
and if it is not priority queue of ints, but some MyClass object?
amitlicht
@eriks You have some options. Either your class defines `operator>`, which would work like charm with `std::greater`. You could write your own functor also instead of `std::greater` if you like.
AraK
@AraK, I think you mean `operator<` ;)
Peter Alexander
@Poita_ Doesn't `std::greater` use `operator>` and `std::less` use `operator<`? Sorry if I am missing something.
AraK
@AraK, @Poita_: Yes, `std::greater` uses `operator>`. @eriks: What AraK said above is the correct way to do this for user-defined types.
James McNellis
The default comparison functor is less<T>, so logically, to reverse the order, you would use greater<T>.
David Smith
+3  A: 

The third template parameter for priority_queue is the comparator. Set it to use greater.

e.g.

std::priority_queue<int, std::vector<int>, std::greater<int> > max_queue;

You'll need #include <functional> for std::greater.

Peter Alexander
`<queue>` is likely to include `<algorithm>` is very likely to include `<functional>`.
Potatoswatter