How to use the priority queue STL for objects?

class Person
{
public:
int age;
};

I want to store objects of the class Person in a priority queue.

priority_queue< Person, vector<Person>, ??? >

I think I need to define a class for the comparison thing, but I am not sure about it.

Also, when we write,

priority_queue< int, vector<int>, greater<int> > ,

How does the greater<int> work?

EDIT:

I found the operator overloading technique quite easy as mentioned by @andbluer. However there is another method I found.

We would write a comparator class, for example:

struct CompareAge {
    bool operator()(Person const & p1, Person const & p2) {
        // return "true" if "p1" is ordered before "p2", for example:
        return p1.age < p2.age;
    }
};

and use that as the comparator argument:

priority_queue<Person, vector<Person>, CompareAge>

What does bool operator() mean here? We are overloading ‘()’? How does it work?

2 Likes

The simplest way is to overload operator<. Keep in mind that the STL priority_queue is a max priority queue and so the element at the top will be the max element. To use it as a min priority queue, change the line “return a.age < b.age;” to “return a.age > b.age;”.

#include <queue>
#include <iostream>
using namespace std;

class Person {
public:
    Person(int age) : age(age) {}
    int age;
};

bool operator<(const Person& a, const Person& b) {
    return a.age < b.age;
}

int main() {
    priority_queue<Person> Q;
    for (int i : {1, 10, 2, 9, 3, 8, 4, 7, 5, 6})
        Q.push(Person(i));
    while (!Q.empty()) {
        Person p = Q.top();
        Q.pop();
        cout << p.age << " ";
    }
    return 0;
}

Output : 10 9 8 7 6 5 4 3 2 1

2 Likes

Thanks a lot @andbluer. It was really helpful. :slight_smile: