How to use the priority queue STL for objects?(如何对对象使用优先队列 STL?)
问题描述
class Person
{
public:
int age;
};
我想将 Person 类的对象存储在优先级队列中.
I want to store objects of the class Person in a priority queue.
priority_queue< Person, vector<Person>, ??? >
我想我需要为比较的东西定义一个类,但我不确定.
I think I need to define a class for the comparison thing, but I am not sure about it.
此外,当我们写作时,
priority_queue< int, vector<int>, greater<int> >
更大的工作如何?
推荐答案
您需要为存储在队列中的类型(在本例中为 Person)提供有效的严格弱排序比较.默认使用 std::less,它解析为与 operator< 等效的内容.这依赖于它自己的存储类型.所以如果你要实施
You need to provide a valid strict weak ordering comparison for the type stored in the queue, Person in this case. The default is to use std::less<T>, which resolves to something equivalent to operator<. This relies on it's own stored type having one. So if you were to implement
bool operator<(const Person& lhs, const Person& rhs);
它应该可以在没有任何进一步更改的情况下工作.实施可能是
it should work without any further changes. The implementation could be
bool operator<(const Person& lhs, const Person& rhs)
{
return lhs.age < rhs.age;
}
如果类型没有自然的小于"比较,提供您自己的谓词会更有意义,而不是默认的std::less.例如,
If the the type does not have a natural "less than" comparison, it would make more sense to provide your own predicate, instead of the default std::less<Person>. For example,
struct LessThanByAge
{
bool operator()(const Person& lhs, const Person& rhs) const
{
return lhs.age < rhs.age;
}
};
然后像这样实例化队列:
then instantiate the queue like this:
std::priority_queue<Person, std::vector<Person>, LessThanByAge> pq;
关于使用 std::greater 作为比较器,这将使用等效于 operator> 并具有创建具有优先级的队列的效果倒置 WRT 默认情况.它需要一个 operator> 可以对两个 Person 实例进行操作.
Concerning the use of std::greater<Person> as comparator, this would use the equivalent of operator> and have the effect of creating a queue with the priority inverted WRT the default case. It would require the presence of an operator> that can operate on two Person instances.
这篇关于如何对对象使用优先队列 STL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何对对象使用优先队列 STL?
基础教程推荐
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 我有静态或动态 boost 库吗? 2021-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 常量变量在标题中不起作用 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
