如何在 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
对象的内存地址来排序的。
声明 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++ 中更常用 - 不要使用原始指针,除非你有充分的理由。
此外,Person
的 operator<
应该被指定为 const
,因为它在任何时候都不应更改它所属的 Person
对象 - [ 的比较器=21=] 期望 const
并且如果 operator<
没有 const
规范则可能会抛出错误。因此,将 operator<
更改为:
bool operator<(const Person& p) const {
return age < p.age;
}
我找不到有关如何在优先级队列中对对象进行排序的任何信息。我试过这个:
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++ 中更常用 - 不要使用原始指针,除非你有充分的理由。
此外,Person
的 operator<
应该被指定为 const
,因为它在任何时候都不应更改它所属的 Person
对象 - [ 的比较器=21=] 期望 const
并且如果 operator<
没有 const
规范则可能会抛出错误。因此,将 operator<
更改为:
bool operator<(const Person& p) const {
return age < p.age;
}