STL priority_queue is the implementation of Heap Data-structure. By default, it’s a max heap and we can easily use it for primitive datatypes. There are some important applications of it which can be found here
Prerequisite: Prioirty_queue Basics
In this article, we will see how can we use priority_queue for custom datatypes like class or structure.
suppose we have a structure name Person which consist of two variables Age and height
and we want to store that in priority_queue then a simple method won’t work here.
Given below is an example of the declaration of struct Person:
C++
struct Person {
int Age;
float Height;
}
|
On defining the Priority Queue as shown below, it’ll give us error since priority_queue doesn’t know on what order(min or max) we need to arrange the objects.
C++
priority_queue<Person> pq;
|
To rectify the error above, we will use operator overloading to define the priority. So that priority_queue can decide how to store the structure object.
Given below is the priority_queue implementation with the structure below:
C++
#include <iostream>
#include <queue>
using namespace std;
#define ROW 5
#define COL 2
struct Person {
int age;
float height;
Person( int age, float height)
: age(age)
, height(height)
{
}
};
struct CompareHeight {
bool operator()(Person const & p1, Person const & p2)
{
return p1.height < p2.height;
}
};
int main()
{
priority_queue<Person, vector<Person>, CompareHeight> Q;
float arr[ROW][COL] = { { 30, 5.5 },
{ 25, 5 },
{ 20, 6 },
{ 33, 6.1 },
{ 23, 5.6 } };
for ( int i = 0; i < ROW; ++i) {
Q.push(Person(arr[i][0], arr[i][1]));
}
while (!Q.empty()) {
Person p = Q.top();
Q.pop();
cout << p.age << " " << p.height << "\n" ;
}
return 0;
}
|
Output
33 6.1
20 6
23 5.6
30 5.5
25 5
Given below is the implementation of priority_queue using Class
C++
#include <iostream>
#include <queue>
using namespace std;
#define ROW 5
#define COL 2
class Person {
public :
int age;
float height;
Person( int age, float height)
: age(age)
, height(height)
{
}
bool operator<( const Person& p) const
{
return this ->height < p.height;
}
};
int main()
{
priority_queue<Person> Q;
float arr[ROW][COL] = { { 30, 5.5 },
{ 25, 5 },
{ 20, 6 },
{ 33, 6.1 },
{ 23, 5.6 } };
for ( int i = 0; i < ROW; ++i) {
Q.push(Person(arr[i][0], arr[i][1]));
}
while (!Q.empty()) {
Person p = Q.top();
Q.pop();
cout << p.age << " " << p.height << "\n" ;
}
return 0;
}
|
Output
33 6.1
20 6
23 5.6
30 5.5
25 5
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!
Last Updated :
09 Oct, 2023
Like Article
Save Article