繁体   English   中英

您如何在C ++中的priority_queue中对对象排序?

[英]How do you order objects in a priority_queue in C++?

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

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对象的内存地址来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 ++中更常用-除非您有充分的理由,否则不要使用原始指针。

此外, operator<Person应该是const规定,因为它不应该改变的Person反对它属于在任何时候-的比较std::priority_queue预计const并可能会抛出一个错误,如果operator<没有const规格。 因此,将operator<更改为:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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