C++中对hash_map自定义哈希函数和比较函数的理解


首先申明一下,我是菜鸟,真正的菜鸟,不是谦虚。所以很多地方有错误,需要大家指出。我只是为了记录,顺便加深自己的理解,不是为了炫耀什么。

这两天学习使用hash_map,在网上搜索了一下,没搜到详细介绍hash_map工作原理的内容(可能是我的搜索方式有问题),然后就自己复制别人的代码,进行修改后使用。就因为是copy别人的代码,就多了后面这些教训了。

做实验用的源代码如下:

  1. #include "stdafx.h" 
  2. #include <iostream>  
  3. #include <hash_map>  
  4. #include <vector></P><P>using std::vector;  
  5. using stdext::hash_map;</P><P>class  hash_wchar_t 
  6. public
  7.  // 以下两个变量我也不是很明白究竟是干嘛的  
  8.  static const size_t   bucket_size = 4;   // 猜测这个变量是初始化hash_map的大小  
  9.  static const size_t   min_buckets = 8;   // 猜测这个变量是每次扩充容量的大小  
  10.  // 以上猜测是根据vector得来的,其实我基本上没使用过STL,只是在C++Primer上看到过,很粗略的看。size_t operator()(const   wchar_t&   GBword) const         
  11.  { 
  12.   return GBword%100;     
  13.   // 下面的那个哈希函数算法是我在网上搜索的说是适合汉字使用的。  
  14.   // 具体适不适合我也不知道,这里测试的时候可以用简单的  
  15.   // return ((unsigned char)GBword-176)*94 + (unsigned char)(GBword>>8) - 161;         
  16.  }   </P><P> bool operator()(const wchar_t& s1,const wchar_t& s2) const         
  17.  {   
  18.   // copy别人代码的时候,由于Key类型是char类型字符串,所以是这么写的  
  19.   // return 0 == strcmp(s1,s2);  
  20.   // 我针对自己使用的Key类型,在修改了参数的形式之后,很天真的就这么使用,这是问题的关键!!  
  21.    
  22.   // 写成这种形式,在下面 测试能否找到的时候,始终出问题,  
  23.   // 原因是p指针指向的是一个未初始化的内存区域,所以无法取数据  
  24.   // 具体原理在代码后面解释  
  25.   return s1 == s2;   </P><P>  // 最后的正确用法  
  26.   // return s1 < s2;   
  27.   // 或者 return s2 > s1;  
  28.  }   
  29. }; 
  30.    
  31. int main() 
  32.  hash_map<const wchar_t,vector<UINT>*,hash_wchar_t> loNameMap; 
  33.  vector<UINT>* lpoVecUint = NULL; 
  34.  lpoVecUint = new vector<UINT>; 
  35.  lpoVecUint->push_back(2);</P><P> loNameMap[L'C'] = lpoVecUint; 
  36.  loNameMap[L'A'] = lpoVecUint; 
  37.  loNameMap[L'B'] = lpoVecUint;</P><P> vector<UINT>* p = loNameMap[L'A'];   // 测试能否找到  
  38.    
  39.  std::cout<<p->size()<<std::endl; 
  40.  return 1; 
  41.    
  42. int main() 
  43.  hash_map<const wchar_t,vector<UINT>*> loNameMap; 
  44.  vector<UINT>* lpoVecUint = NULL; 
  45.  lpoVecUint = new vector<UINT>; 
  46.  lpoVecUint->push_back(2);</P><P> loNameMap[L'C'] = lpoVecUint; 
  47.  loNameMap[L'A'] = lpoVecUint; 
  48.  loNameMap[L'B'] = lpoVecUint;</P><P> vector<UINT>* p = loNameMap[L'A'];   // 测试能否找到  
  49.    
  50.  std::cout<<p->size()<<std::endl; 
  51.  return 1; 
  52. }
  • 1
  • 2
  • 下一页

相关内容