我找不到任何关于如何在优先级队列中对对象进行排序的信息。我试过这个:
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/