1

I couldn't find any information on how to order objects in a priority queue. I tried this:

class Person {
    ...
    public:
    bool operator<(const Person& p) {
        return age < p.age;
    }
}

int main() {
    priority_queue<Person*> people;
    people.push(new Person("YoungMan", 21));
    people.push(new Person("Grandma", 83));
    people.push(new Person("TimeTraveler", -5000));
    people.push(new Person("Infant", 1));

    while (!people.empty()) {
        cout << people.top()->name;
        delete people.top();
        people.pop();
    }

And it's supposed to give priority based on age (older people get higher priority, and thus leave the queue first), but it doesn't work. But I'm getting this output:

Infant
Grandma
TimeTraveler
YoungMan

And I have no idea what this is ordered by, but it's definitely not age.

1
  • 1
    You have a priority_queue of pointers, it's sorting using the value of the pointers not the age. Use priority_queue<Person> and remove the news when you push. Jul 20, 2016 at 23:51

1 Answer 1

8

priority_queue<Person*> actually orders based on comparing the memory addresses of Person object using the comparator std::less<Person*>.

Declare a priority_queue<Person> instead to order based on the operator< you provided.

Or if you insist on using pointers (for some reason) then declare as:

auto age_comp = [](const std::unique_ptr<Person>& lhs, const std::unique_ptr<Person>& rhs) -> bool {
    return *lhs < *rhs;
};
std::priority_queue<std::unique_ptr<Person>, std::vector<std::unique_ptr<Person>>,
    decltype(age_comp)> people(age_comp);
// note: must pass age_comp to std::priority_queue constructor here as
// lambda closure types have deleted default constructors

Note that this is using smart pointers not raw pointers, the former are much more commonly used in modern C++ - don't use raw pointers unless you have a very good reason to.

Also, operator< of Person should be const specified as it shouldn't change the Person object it belongs to at any point - the comparator of std::priority_queue expects the const and will likely throw an error if the operator< does not have const specification. So, alter operator< to:

bool operator<(const Person& p) const {
    return age < p.age;
}
2
  • This works, thanks. Also, I got an error which implied that I need to add const after the operator overloading function (before the body part). Why is const necessary here? Jul 21, 2016 at 0:02
  • Ah yes, operator< should have a const specification as it shouldn't change this - the comparator of std::priority_queue expects it to be const specified so its necessary (and correct) here. Jul 21, 2016 at 0:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.