Open In App

C++ STL – Reverse Priority Queue

Improve
Improve
Like Article
Like
Save
Share
Report

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++




// C++ program to demonstrate priority 
// queue in reverse order
#include <iostream>
#include <queue>
using namespace std;
  
int main()
{
    // Initialising the priority queue
    priority_queue<int, vector<int>, greater<int> > pq;
    
    // Inserting values in priority queue
    pq.push(10);
    pq.push(30);
    pq.push(20);
    pq.push(15);
    pq.push(25);
  
    cout << "The priority queue in reverse order is : ";
      
    // Printing all elements in priority queue
    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++




// C++ program to demonstrate priority queue in reverse order
#include <bits/stdc++.h>
using namespace std;
  
int main()
{
    // Initialising the priority queue
    priority_queue<string, vector<string>, greater<string> > pq;
      
    // Inserting values in priority queue
    pq.push("physics");
    pq.push("chemistry");
    pq.push("maths");
    pq.push("socialstudies");
    pq.push("biology");
  
    cout << "The priority queue in reverse order is : ";
      
    // Printing all elements in priority queue
    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?



Last Updated : 02 Nov, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads