【发布时间】:2020-10-14 14:46:07
【问题描述】:
我想在unordered_set 中使用我的数据类型。它没有用,但this SO question 帮助理解了我需要做的事情。
This answer 但是让我很困惑我应该在哈希结构中放入什么。
我的哈希现在应该返回x.name.size() 还是x.hash?
我的数据类型:
struct State {
std::string name;
std::size_t hash = std::hash<std::string>{}(name);
bool operator==(const State &rhs) const;
bool operator!=(const State &rhs) const;
};
我应该使用 A 还是 B ?
namespace std {
template<>
struct hash<State>{
typedef State argument_type;
typedef std::size_t result_type;
size_t operator()(const foundation::State& x) const{
// A.) return x.name.size();
// B.) return x.hash;
}
};
}
【问题讨论】:
-
return x.hash;会起作用,但要注意将哈希存储为成员是一种权衡。每次State的状态发生变化时,您都需要显式刷新该哈希值。从技术上讲,return x.name.size();也可以,但它可能会导致你的系列表现非常糟糕。 -
在任何情况下,您的哈希都是字符串的长度,您要求将其存储为成员还是在每次调用时重新计算?
标签: c++