侯捷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<T>()(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 }
View Code
复制代码

例如

复制代码
 1 #include<functional>
 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 }
View Code
复制代码

 

posted @   80k  阅读(168)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示