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?
Learn to code easily with our course
Coding for Everyone. This course is accessible and designed for everyone, even if you're new to coding. Start today and join millions on a journey to improve your skills!Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Commit to GfG's Three-90 Challenge! Purchase a course, complete 90% in 90 days, and save 90% cost click here to explore.
Last Updated :
02 Nov, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...