如何在C ++中使用std :: unordered_set?

时间:2014-03-26 20:24:33

标签: c++ hash

我在Java中选择了哈希表的概念,所以我知道对于泛型"哈希集"要为自定义类工作的容器,必须为哈希函数和相应的相等函数提供定义。

在Java中,这意味着重写方法

int hashCode()

boolean equals (Object o)

我在c ++的STL中期待相同的逻辑,但是在理解语法方面遇到了困难。具体来说,std :: unordered_set<>接受5个模板参数(你能相信吗?),它看起来像一个怪物,让我头晕目眩。

所以如果能为当前的玩具类提供一个简单的例子,我将不胜感激:

class Some{
public :
int a;
};

其中哈希函数只返回a的值,如果成员' a'的值,则相等测试函数返回true。是一样的。

由于

2 个答案:

答案 0 :(得分:4)

第1步:为您的类型重载operator==

bool operator==(const Some& x, const Some& y)
{
    return x.a == y.a;
}

第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;
        }
    };
}

第3步:简单测试:

int main()
{
    std::unordered_set<Some> test;
    test.insert(Some{42});
}

第4步:获利!

答案 1 :(得分:1)

我没有编译器,因此可能存在错误,但它应该类似于:

namespace std {
  template <>
  struct hash<Some>
  {
    typedef Some argument_type;
    typedef std::size_t  result_type;

    result_type operator()(const Some & t) const
    {
       return t.a;
    }
  };
}