侯捷C++万用的hash function


课程中提供的,hash_val函数,输入参数为类的全部数据,返回值为std:stze_t的哈希值

 1  
 2 template<class T>
 3 inline  void  hash_combine(std::size_t & seed, const T & val){
 4     seed ^= hash()(val)+0x9e3779b9 + (seed << 6) + (seed >> 2);
 5 }
 6 template<class T>
 7 inline  void  hash_val(std::size_t & seed, const T & val){
 8     hash_combine(seed, val);
 9 }
10  
11 template<class T,class ...Types>
12 inline  void  hash_val(std::size_t & seed, const T & val,const Types & ...args){
13     hash_combine(seed, val);
14     hash_val(seed, args...);
15 }
16  
17  
18 template<class ...Types>
19 inline  size_t  hash_val(const Types & ...args){
20     size_t  seed = 0;
21     hash_val(seed, args...);
22     return seed;
23 }

例如

 1 #include
 2 
 3 class C
 4 
 5 {
 6 
 7   type1 arg1;
 8 
 9   type2 arg2;
10 
11   type3 arg3;
12 
13 };
14 
15 
16 
17 class CHash
18 
19 {
20 
21 public:
22 
23   std:size_t operator(const C& c) const
24 
25   {
26 
27     return hash_val(c.arg1,c.arg2,c.arg3);
28   }
29 
30 }