[英]Modify std::less on a shared_ptr
这就是我所拥有的:
struct Foo {
int index;
}
std::set<std::shared_ptr<Foo>> bar;
我想通过它们的索引而不是通过默认的std::less<std::shared_ptr<T>>
函数来对bar
的元素进行排序,该函数与指针相关。
我读到我可以键入
std::set<std::shared_ptr<Foo>, std::owner_less<std::shared_ptr<Foo>>> bar
,但是我更喜欢坚持以前的语法。
我尝试定义std::less<std::shared_ptr<Foo>>
,但是set
函数实际上并未使用它。 有没有办法可以做到这一点?
如果要按其索引进行比较,则必须编写一个按其索引进行检查的比较器。 std::less<>
会做错事(因为它不会知道index
),而std::owner_less<>
会做错事(因为它仍然不会比较Foo
,但是必须这样做以及它们的所有权语义)。
您必须写:
struct SharedFooComparator {
bool operator()(const std::shared_ptr<Foo>& lhs,
const std::shared_ptr<Foo>& rhs) const
{
return lhs->index < rhs->index;
}
};
并使用它:
std::set<std::shared_ptr<Foo>, SharedFooComparator> bar;
您还可以将其通用化为shared_ptr的通用比较器:
struct SharedComparator {
template <typename T>
bool operator()(const std::shared_ptr<T>& lhs,
const std::shared_ptr<T>& rhs) const
{
return (*lhs) < (*rhs);
}
};
然后简单地使Foo
具有可比性。
您可以在std
名称空间中提供您自己的less<shared_ptr<Foo>>
专业化。
namespace std
{
template<>
class less<shared_ptr<Foo>>
{
public:
bool operator()(const shared_ptr<Event>& a, const shared_ptr<Event>& b)
{
// Compare *a and *b in some way
}
};
}
然后,您可以在没有比较器的情况下形成set<shared_ptr<Foo>>
。 我需要一个priority_queue<shared_ptr<Foo>>
,我不想在其中使用priority_queue<Foo*, vector<Foo*>, int (*)(const Foo*, const Foo*)>
。 我不为此感到骄傲,但它确实有效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.