【问题标题】:How to properly hash the custom struct?如何正确散列自定义结构?
【发布时间】:2013-10-12 06:37:21
【问题描述】:

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

那么,我有一个结构:

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

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

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

【问题讨论】:

    标签: c++ hash probability


    【解决方案1】:

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

    请参阅提升文档here

    【讨论】:

      【解决方案2】:

      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&lt;S&gt; s;

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多