1. 程式人生 > >C++中對hash_map自定義雜湊函式和比較函式的理解

C++中對hash_map自定義雜湊函式和比較函式的理解

#include "stdafx.h" #include <iostream> #include <hash_map> #include <vector>

using std::vector; using stdext::hash_map;

class  hash_wchar_t { public:  // 以下兩個變數我也不是很明白究竟是幹嘛的  static const size_t   bucket_size = 4;   // 猜測這個變數是初始化hash_map的大小  static const size_t   min_buckets = 8;   // 猜測這個變數是每次擴充容量的大小  // 以上猜測是根據vector得來的,其實我基本上沒使用過STL,只是在C++Primer上看到過,很粗略的看。

 size_t operator()(const   wchar_t&   GBword) const        {   return GBword%100;       // 下面的那個雜湊函式演算法是我在網上搜索的說是適合漢字使用的。   // 具體適不適合我也不知道,這裡測試的時候可以用簡單的   // return ((unsigned char)GBword-176)*94 + (unsigned char)(GBword>>8) - 161;        }  

 bool operator()(const wchar_t& s1,const wchar_t& s2) const        {    // copy別人程式碼的時候,由於Key型別是char型別字串,所以是這麼寫的   // return 0 == strcmp(s1,s2);   // 我針對自己使用的Key型別,在修改了引數的形式之後,很天真的就這麼使用,這是問題的關鍵!!      // 寫成這種形式,在下面 測試能否找到的時候,始終出問題,   // 原因是p指標指向的是一個未初始化的記憶體區域,所以無法取資料   // 具體原理在程式碼後面解釋   return s1 == s2;   

  // 最後的正確用法   // return s1 < s2;   // 或者 return s2 > s1;  }  };

  int main() {  hash_map<const wchar_t,vector<UINT>*,hash_wchar_t> loNameMap;  vector<UINT>* lpoVecUint = NULL;  lpoVecUint = new vector<UINT>;  lpoVecUint->push_back(2);

 loNameMap[L'C'] = lpoVecUint;  loNameMap[L'A'] = lpoVecUint;  loNameMap[L'B'] = lpoVecUint;

 vector<UINT>* p = loNameMap[L'A'];   // 測試能否找到    std::cout<<p->size()<<std::endl;  return 1; }   int main() {  hash_map<const wchar_t,vector<UINT>*> loNameMap;  vector<UINT>* lpoVecUint = NULL;  lpoVecUint = new vector<UINT>;  lpoVecUint->push_back(2);

 loNameMap[L'C'] = lpoVecUint;  loNameMap[L'A'] = lpoVecUint;  loNameMap[L'B'] = lpoVecUint;

 vector<UINT>* p = loNameMap[L'A'];   // 測試能否找到    std::cout<<p->size()<<std::endl;  return 1; }