歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> C++中對hash_map自定義哈希函數和比較函數的理解

C++中對hash_map自定義哈希函數和比較函數的理解

日期:2017/3/1 10:07:41   编辑:Linux編程

首先申明一下,我是菜鳥,真正的菜鳥,不是謙虛。所以很多地方有錯誤,需要大家指出。我只是為了記錄,順便加深自己的理解,不是為了炫耀什麼。

這兩天學習使用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. {
  7. public:
  8. // 以下兩個變量我也不是很明白究竟是干嘛的
  9. static const size_t bucket_size = 4; // 猜測這個變量是初始化hash_map的大小
  10. static const size_t min_buckets = 8; // 猜測這個變量是每次擴充容量的大小
  11. // 以上猜測是根據vector得來的,其實我基本上沒使用過STL,只是在C++Primer上看到過,很粗略的看。size_t operator()(const wchar_t& GBword) const
  12. {
  13. return GBword%100;
  14. // 下面的那個哈希函數算法是我在網上搜索的說是適合漢字使用的。
  15. // 具體適不適合我也不知道,這裡測試的時候可以用簡單的
  16. // return ((unsigned char)GBword-176)*94 + (unsigned char)(GBword>>8) - 161;
  17. } </P><P> bool operator()(const wchar_t& s1,const wchar_t& s2) const
  18. {
  19. // copy別人代碼的時候,由於Key類型是char類型字符串,所以是這麼寫的
  20. // return 0 == strcmp(s1,s2);
  21. // 我針對自己使用的Key類型,在修改了參數的形式之後,很天真的就這麼使用,這是問題的關鍵!!
  22. // 寫成這種形式,在下面 測試能否找到的時候,始終出問題,
  23. // 原因是p指針指向的是一個未初始化的內存區域,所以無法取數據
  24. // 具體原理在代碼後面解釋
  25. return s1 == s2; </P><P> // 最後的正確用法
  26. // return s1 < s2;
  27. // 或者 return s2 > s1;
  28. }
  29. };
  30. int main()
  31. {
  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. std::cout<<p->size()<<std::endl;
  39. return 1;
  40. }
  41. int main()
  42. {
  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. std::cout<<p->size()<<std::endl;
  50. return 1;
  51. }
Copyright © Linux教程網 All Rights Reserved