Min priority_queue in C++

Taohidul Islam
1 min readJan 8, 2019

--

In C++, the default STL (Standard Template Library) priority queue is Max priority queue (returns the largest element).

Output : 3 2 1

Here, we’re getting the highest of the current values. This is a max priority queue. We can use this priority queue as Min priority queue by applying some interesting tricks. Let’s start!

1. Using greater as comparison function :

Output : 1 2 3

Now, we’re getting the minimum value first!

2. Using opposite sign

We can obtain min priority queue by inserting values by changing sign (using minus (-) for positive number and using plus (+) for negative number :

Output : -4 1 2 3

Look at the line number 13. We need to negate the value (again) to get the original value.

3. Using custom structure or class :

Output : 1 2 3

Actually, Using custom structure or class we can use priority_queue in any order.

Suppose, we want to sort people in descending order according to their salary and if tie then according to their age.

Output :

80 40
100 40
100 50

Same result can be obtained by operator overloading :

Output :

80 40
100 40
100 50

So, we can use C++ priority queue as our requirement by using these interesting tricks! :)

You can also read :

  1. Understanding Python decorators
  2. Functions as first class object in Python
  3. Playing with inheritance in Python
  4. Closure in Python and Javascript
  5. React navigation cheatsheet

--

--