如何在C++中的priority_queue中订购对象?

Cof*_*ker 0 c++ priority-queue

我找不到有关如何在优先级队列中订购对象的任何信息.我试过这个:

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();
    }
Run Code Online (Sandbox Code Playgroud)

并且它应该根据年龄给予优先级(老年人获得更高的优先级,因此将队列排在第一位),但它不起作用.但是我得到了这个输出:

Infant
Grandma
TimeTraveler
YoungMan
Run Code Online (Sandbox Code Playgroud)

我不知道这是什么命令,但它绝对不是年龄.

sjr*_*son 7

priority_queue<Person*>实际上是基于Person使用比较器比较对象的内存地址的命令std::less<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
Run Code Online (Sandbox Code Playgroud)

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

此外,operator<Person应当const规定,因为它不应该改变Person它属于在任何时候物体-的比较std::priority_queue预期const,并可能会抛出一个错误,如果operator<没有const规范.所以,operator<改为:

bool operator<(const Person& p) const {
    return age < p.age;
}
Run Code Online (Sandbox Code Playgroud)