我在 Java 中选择了哈希表的概念,因此我意识到要为自定义类工作的通用“哈希集”容器,必须为哈希函数和相应的相等函数提供定义。
在 Java 中,这意味着覆盖方法
int hashCode()
Run Code Online (Sandbox Code Playgroud)
和
boolean equals (Object o)
Run Code Online (Sandbox Code Playgroud)
.
我期待在 C++ 的 STL 中使用相同的逻辑,但是在理解语法时遇到了麻烦。具体来说, std::unordered_set<> 接受 5 个模板参数(你相信吗?),这看起来像个怪物,让我头晕目眩。
因此,如果有人能为当前的玩具类举一个简单的例子,我将不胜感激:
class Some{
public :
int a;
};
Run Code Online (Sandbox Code Playgroud)
其中哈希函数只返回 a 的值,而等式测试函数返回 true 且仅当成员 'a' 的值相同。
谢谢
第 1 步:operator==为您的类型重载:
bool operator==(const Some& x, const Some& y)
{
return x.a == y.a;
}
Run Code Online (Sandbox Code Playgroud)
第 2 步:专门std::hash针对您的类型:
namespace std
{
template<>
struct hash<Some>
{
typedef Some argument_type;
typedef size_t result_type;
size_t operator()(const Some& x) const
{
return x.a;
}
};
}
Run Code Online (Sandbox Code Playgroud)
第 3 步:一个简单的测试:
int main()
{
std::unordered_set<Some> test;
test.insert(Some{42});
}
Run Code Online (Sandbox Code Playgroud)
第 4 步:获利!