c++ - 你如何在 C++ 中的 priority_queue 中排序对象?

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

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

Infant
Grandma
TimeTraveler
YoungMan

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

最佳答案

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

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

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

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

关于c++ - 你如何在 C++ 中的 priority_queue 中排序对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38492612/

相关文章:

java - 使用 MultiMap 的优先级队列 - Java

java - 实现 PriorityQueue 协助

java - 优先级队列插入键值对java

c++ - 每个窗口的 Win32 api 不同类?

c++ - eigen::vectorXf 到 MatriXf 映射

c++ - 使用大括号初始化类实例

cluster-computing - 多用户集群: IBM Platform LSF: user changing priority of jobs

c++ - Visual C++ 错误

c++ - 如何将 vector 转换为矩阵 C++ vec2mat

c++ - std::priority_queue 的模板参数是什么?