16

在 C++ 语言中,std::hash<T>对于最简单的类型,如std::stringint等,有默认的哈希函数模板。我想,这些函数具有良好的熵,并且相应的随机变量分布在统计上是均匀的。如果不是,那么让我们假装它是。

然后,我有一个结构:

struct CustomType {
  int field1;
  short field2;
  string field3;
  // ...
};

我想对它进行散列,使用其中一些字段的单独散列,比如std::hash(field1)std::hash(field2). 两个哈希都在 type 的一组可能值中size_t

什么是一个好的散列函数,它可以结合这两个结果并将它们映射回size_t

4

2 回答 2

17

boost::hash_combine散列不同字段真的很好。

如果你没有 boost 库,你可以使用这个:

template <class T>
inline void hash_combine(std::size_t & s, const T & v)
{
  std::hash<T> h;
  s^= h(v) + 0x9e3779b9 + (s<< 6) + (s>> 2);
}

 struct S {
  int field1;
  short field2;
  std::string field3;
  // ...
};

template <class T>
class MyHash;

template<>
struct MyHash<S>
{
    std::size_t operator()(S const& s) const 
    {
        std::size_t res = 0;
       hash_combine(res,s.field1);
       hash_combine(res,s.field2);
       hash_combine(res,s.field3);
        return res;
    }
};

然后大概 std::unordered_set<S> s;,等等

于 2013-10-05T07:52:47.120 回答
9

boost::hash_combine在这里可以帮助您:

namespace std
{
template <>
struct hash<CustomType>
{
    std::size_t operator()(const CustomType& c) const
    {
        std::size_t result = 0;
        boost::hash_combine(result, field1);
        boost::hash_combine(result, field2);
        return result;
    }
};
}

请参阅此处的 boost 文档。

于 2013-10-05T07:30:12.023 回答