我有以下结构
struct MyClass {
int myInt;
std::map<int, int> myMap;
};
Run Code Online (Sandbox Code Playgroud)
我想使用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;
}
Run Code Online (Sandbox Code Playgroud)
我希望一切都好,但我找不到一种方式来声明PointedObjEq
- - 编辑 - -
如果在类调试中声明operator==永远不会中断,但我认为因为MyClass == MyClass*永远不会发生......
struct MyClass {
...
...
bool operator==(MyClass* const& c) {
return this->myInt == c->myInt & this->myMap == c->myMap;
}
Run Code Online (Sandbox Code Playgroud)
如果在类调试中声明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;
}
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8178 次 |
| 最近记录: |