如何在C ++中使用std :: unordered_set? [英] How to use std::unordered_set in C++?
问题描述
我选择了Java中的哈希表的概念,所以我意识到,对于用于定制类的通用哈希集合容器,必须为散列函数和相应的相等函数提供定义。
在Java中,这意味着重写方法
int hashCode()
和
boolean equals(Object o)
。
<我期待着c ++ STL中的相同逻辑,但是在理解语法时遇到困难。具体来说,std :: unordered_set<>接受5个模板参数(你能相信吗?),它看起来像一个怪物,并让我的头旋转。
感谢它,如果可以给出一个简单的例子,当前的玩具类:
class一些{
public:
int a;
};
其中hash函数只返回a的值,并且相等测试函数返回true iff成员'a'的值是相同的。
谢谢
步骤1:为您的类型重载 operator ==
:
bool operator ==(const Some& x,const Some& y)
{
return xa == ya;
$ / code>
第二步:专用 std :: hash
$ b
namespace std
{
template<> code>
struct hash< Some>
{
typedef一些argument_type;
typedef size_t result_type;
size_t operator()(const Some& x)const
{
return x.a;
}
};
}
第3步:简单测试:
int main()
{
std :: unordered_set< Some>测试;
test.insert(一些{42});
}
第四步:获利!
I picked the concepts of hash tables in Java, so I was aware that for a generic "hash set" container to work for custom classes, one must provide definition for a hash function and an corresponding equality function.
In Java, this would mean overriding method
int hashCode()
and
boolean equals (Object o)
.
I was expecting the same logic in c++'s STL, but was having trouble understanding the syntax. Specifically, std::unordered_set<> accepts 5 template arguments (can you believe that?), which looks like a monster and makes my head spin.
So I would be appreciate it if one could give a simple example for the current toy class:
class Some{
public :
int a;
};
Of which the hash function simply returns the value of a, and the equality test functions returns true iff the values of member 'a' are the same.
Thanks
Step 1: Overload operator==
for your type:
bool operator==(const Some& x, const Some& y)
{
return x.a == y.a;
}
Step 2: Specialize std::hash
for your type:
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;
}
};
}
Step 3: A simple test:
int main()
{
std::unordered_set<Some> test;
test.insert(Some{42});
}
Step 4: Profit!
这篇关于如何在C ++中使用std :: unordered_set?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!