如何正确地散列自定义结构? 在C++语言中,对于最简单的类型,如“代码> STD::String < /COD>, INT/COD>”等,存在默认的哈希函数模板 STD::HASH 。如果不是,那么让我们假装是

如何正确地散列自定义结构? 在C++语言中,对于最简单的类型,如“代码> STD::String < /COD>, INT/COD>”等,存在默认的哈希函数模板 STD::HASH 。如果不是,那么让我们假装是,c++,hash,probability,C++,Hash,Probability,然后,我有一个结构: struct CustomType { int field1; short field2; string field3; // ... }; 我想对它进行散列,使用它的一些字段的单独散列,例如,std::hash(field1)和std::hash(field2)。这两个散列都位于类型为size\u t的一组可能值中 什么是好的散列函数,它可以组合这两个结果并将它们映射回size\t?boost::hash\u combine可以帮助您: namespac

然后,我有一个结构:

struct CustomType {
  int field1;
  short field2;
  string field3;
  // ...
};
我想对它进行散列,使用它的一些字段的单独散列,例如,
std::hash(field1)
std::hash(field2)
。这两个散列都位于类型为
size\u t
的一组可能值中


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

boost::hash\u 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;
    }
};
}
名称空间std
{
模板
结构散列
{
std::size\u t运算符()(const CustomType&c)const
{
标准::大小\u t结果=0;
boost::hash_combine(结果,字段1);
boost::hash_combine(结果,字段2);
返回结果;
}
};
}

查看boost文档。

boost::hash\u 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;
    }
};
模板
内联无效哈希组合(标准::大小t&s,常数t&v)
{
std::hash;
s^=h(v)+0x9e3779b9+(s>2);
}
结构{
int field1;
短域2;
std::字符串字段3;
// ...
};
模板
类MyHash;
模板
结构MyHash
{
std::size\u t运算符()(S常量&S)常量
{
标准:尺寸=0;
哈希_组合(res,s.field1);
哈希_组合(res,s.field2);
哈希_组合(res,s.field3);
返回res;
}
};
然后可能是
std::无序的集合,等

读取