std::unordered_set of pointers
std::unordered_set of pointers
我有以下结构体
struct MyClass {
int myInt;
std::map<int, int> myMap;
};
我想使用unordered_set<MyClass*, PointedObjHash, PointedObEq>
,但我找不到一个有效的方式来声明PointedObEq
。
我试着
struct PointedObjHash {
size_t operator() (MyClass* const& c) const {
std::size_t seed = 0;
boost::hash_combine(seed, c->myInt);
boost::hash_combine(seed, c->myMap);
return seed;
}
和我希望它是好的,但我找不到一种方法来声明PointedObjEq
—EDIT—
如果declare operator==在类内调试永远不会中断,但我认为因为MyClass == MyClass*永远不会发生…
struct MyClass {
...
...
bool operator==(MyClass* const& c) {
return this->myInt == c->myInt & this->myMap == c->myMap;
}
如果declare operator==在类内调试永远不会中断,但我认为因为MyClass == MyClass*永远不会发生…
unordered_set
需要使用operator==
(或PointedObjEq
)来复查哈希函数的结果。哈希提供了近似的等式,等式函数用于剔除误报。
如果你已经测试了两次向集合添加相同的值,那么你已经测试了相等函数。当然,可以让它打印一些东西到控制台。
由于不可能定义具有两个指针操作数的operator==
函数,因此必须使用PointedObjEq
类。注意,它的两边都有一个MyClass const *
。同样,也不需要使用指针的引用。
struct PointedObjEq {
bool operator () ( MyClass const * lhs, MyClass const * rhs ) const {
return lhs->myInt == rhs->myInt
&& lhs->myMap == rhs->myMap;
}
};
应该这样做:
struct PointedObEq {
bool operator()(MyClass const * lhs, MyClass const * rhs) const {
return lhs->myInt == rhs->myInt && lhs->myMap == rhs->myMap;
}
};
你的解决方案不起作用的原因是因为你有效地编写了一个机制来比较MyClass
和MyClass*
,当你真正需要比较MyClass*
和MyClass*
的时候。
注::我最初的答案通过const&
传递了指针。仔细想想,这是一种奇怪的编码风格,所以我把它改成了按值传递指针。
typedef MyClass* PtrMyClass;
struct PointedObjCompare
{ // functor for operator==
bool operator()(const PtrMyClass& lhs, const PtrMyClass& rhs) const
{
// your code goes here
}
};
std::unordered_set < MyClass*, PointedObjHash, PointedObjCompare > myset;
相关文章:
- Usages of std::move
- 使用 [] 运算符时"binding reference of type discards qualifiers"
- 如何处理 c++ 中类实现中的"invalid use of non-static data member"?
- 具有变量Number of Arguments的std::函数的矢量
- Capacity of a deque
- Deprecation of _writeBarrier()
- constexpr begin of a std::array
- 如何调整 std::vector of Eigen::MatrixXd 的大小
- C++ "error: invalid use of void expression"
- 我看到"use of undeclared identifier"错误,有人可以告诉我如何解决它吗?
- 赛通"Cannot take address of memoryview slice"
- C++ Version Of Double.longBitsToDouble
- 收到错误"invalid use of non-static data member 'stu::n' "
- C++ Usage of AsyncCallback
- 错误:"Left of getValue must have class/struct/union"
- Centos7 g++ "to_string is not in a member of std"
- 在C++中使用 Catch 测试框架编译错误"error: expected ';' at end of declaration list"
- One-past-end-of-object pointers
- "vector of objects"大小与"vector of Object pointers"
- std::unordered_set of pointers