简体   繁体   中英

How do you order objects in a priority_queue in C++?

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.

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM