priorityqueue-如何在C++中对priority_queue中的对象进行排序
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
对象——std::priority_queue
的比较器期望const
,如果operator<
没有const
规范,则可能会抛出错误。因此,将operator<
更改为:
bool operator<(const Person& p) const {
return age < p.age;
}
相关文章:
- 在c++中尝试对对象数组进行排序时,出现std:bad_alloc错误
- 对象接收堆栈溢出异常 c++ 的排序向量
- 如何使用 STL 排序对具有模板专用化的自定义类对象进行排序?
- 排序谓词没有传递对索引对象的引用?
- 使用指针指向对象C++对向量进行排序
- 按类成员的顺序对包含类对象的C++向量进行排序
- 无法使用接口类型对priority_queue中的对象进行排序<T>
- 基于不同字段的对象向量的排序功能
- 基于3个对象的自定义排序
- 尝试使用比较运算符对对象向量进行排序
- C++排序的对象集
- 从文件中读取并将其内容放入对象数组中,然后对它们进行排序
- q排序类对象的列表
- std::atexit 从全局对象的构造函数调用时的排序
- 尝试对对象数组进行排序时程序终止
- std::排序为排序自定义对象时出现的向量引发错误
- 通过其char键对对象指针的C 向量进行排序
- 排序算法,使用模板按内部数据对对象进行排序
- 在对象向量中的对象字段排序
- 如何使用 std::sort 对数组中的特定对象进行排序