Meaning of below Statement

What is mean of below statement?

priority_queue<pii,vector,greater >q;

Please tell me…

Refer to: http://www.cplusplus.com/reference/queue/priority_queue/

Assuming pii stands for pair < int, int > (which is a common macro used by programmers) the above statement means that you are declaring a priority queue of type pair < int, int > with it’s underlying container as a vector of pair of integers and that the heap created will be a min-heap (change greater to less to make it max-heap or simply remove it; max-heap by default).

Another good reference which, in fact uses the above statement : c++ - How can I create Min stl priority_queue? - Stack Overflow

In case this answers your query, please mark it as accepted.

2 Likes

Pii is a macro generally used for pair<int,int>. priority_queue<pii,vector,greater >q creates a min priority queue.

Priority queue is like normal queue except that elements get popped on the basis of priority.Last parameter is a template which is our comparator function to create our priority queue.By default, max priority queue is created.

Using greater here means that lower values are considered of higher priority and come out of the priority queue earlier. By default less is used, and higher values are higher priority.

Pairs are ordered lexicographically; (1, 3) comes before (2, 1) and after (1, 2).

Thus, we get a min priority queue. Priority queues are quite important for implementation of heap and a very stable sorting algorithm called heap sort.

Hope it helps

1 Like

Please say …
#define pii pair<int , int>
priority_queue< pii,vector, greater >q;
Please how to convert to min heap.

2 ways to do so.

  1. Use ‘less’ instead of ‘greater’
  2. Completely remove greater as less is used by default.
1 Like

Tnq utkarsh1997.