C++ STL – Reverse Priority Queue
Last Updated :
02 Nov, 2022
A priority Queue is an abstract data type that resembles a queue, and each element has a corresponding priority value. Priority queues are built on the top of the max heap and use an array or vector as an internal structure.
In C++ STL, by default, the first element of the queue is the greatest of all elements in the queue and elements are in nonincreasing order. But however, we can make a priority queue having the smallest element at the top as min-heap with the help of greater<data_type> in C++ STL.
Syntax:
priority_queue <data_type, vector<data_type>, greater<data_type>> variable_name;
Example:
C++
#include <iostream>
#include <queue>
using namespace std;
int main()
{
priority_queue< int , vector< int >, greater< int > > pq;
pq.push(10);
pq.push(30);
pq.push(20);
pq.push(15);
pq.push(25);
cout << "The priority queue in reverse order is : " ;
while (!pq.empty())
{
cout<<pq.top()<< " " ;
pq.pop();
}
return 0;
}
|
Output
The priority queue in reverse order is : 10 15 20 25 30
Example:
C++
#include <bits/stdc++.h>
using namespace std;
int main()
{
priority_queue<string, vector<string>, greater<string> > pq;
pq.push( "physics" );
pq.push( "chemistry" );
pq.push( "maths" );
pq.push( "socialstudies" );
pq.push( "biology" );
cout << "The priority queue in reverse order is : " ;
while (!pq.empty())
{
cout<<pq.top()<< " " ;
pq.pop();
}
return 0;
}
|
Output
The priority queue in reverse order is : biology chemistry maths physics socialstudies
For more information, refer to the article – How to implement Min Heap using STL?
Share your thoughts in the comments
Please Login to comment...