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?
基础教程推荐
- Windows Media Foundation 录制音频 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 从 std::cin 读取密码 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01