priorityqueue-如何在C++中对priority_queue中的对象进行排序

priority queue - How do you order objects in a priority_queue in C++?

本文关键字:对象 排序 queue C++ priority 中对 priorityqueue-      更新时间:2023-10-16

我找不到任何关于如何在优先级队列中排序对象的信息。我试过这个:

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

它应该根据年龄给予优先级(老年人的优先级更高,因此会先离开队列),但它不起作用。但我得到了这个输出:

Infant
Grandma
TimeTraveler
YoungMan

我不知道这是按什么顺序排列的,但这绝对不是年龄。

priority_queue<Person*>实际上是基于使用比较器std::less<Person*>比较Person对象的内存地址来排序的。

声明一个priority_queue<Person>,以根据您提供的operator<进行订购。

或者,如果您坚持使用指针(出于某种原因),则声明为:

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

注意,这是使用智能指针而不是原始指针,前者在现代C++中更常用——除非你有充分的理由,否则不要使用原始指针。

此外,Personoperator<应该指定为const,因为它在任何时候都不应该更改它所属的Person对象——std::priority_queue的比较器期望const,如果operator<没有const规范,则可能会抛出错误。因此,将operator<更改为:

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