C++中对hash_map自定义哈希函数和比较函数的理解
C++中对hash_map自定义哈希函数和比较函数的理解
首先申明一下,我是菜鸟,真正的菜鸟,不是谦虚。所以很多地方有错误,需要大家指出。我只是为了记录,顺便加深自己的理解,不是为了炫耀什么。
这两天学习使用hash_map,在网上搜索了一下,没搜到详细介绍hash_map工作原理的内容(可能是我的搜索方式有问题),然后就自己复制别人的代码,进行修改后使用。就因为是copy别人的代码,就多了后面这些教训了。
做实验用的源代码如下:
- #include "stdafx.h"
- #include <iostream>
- #include <hash_map>
- #include <vector></P><P>using std::vector;
- using stdext::hash_map;</P><P>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;
- } </P><P> bool operator()(const wchar_t& s1,const wchar_t& s2) const
- {
- // copy别人代码的时候,由于Key类型是char类型字符串,所以是这么写的
- // return 0 == strcmp(s1,s2);
- // 我针对自己使用的Key类型,在修改了参数的形式之后,很天真的就这么使用,这是问题的关键!!
- // 写成这种形式,在下面 测试能否找到的时候,始终出问题,
- // 原因是p指针指向的是一个未初始化的内存区域,所以无法取数据
- // 具体原理在代码后面解释
- return s1 == s2; </P><P> // 最后的正确用法
- // 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);</P><P> loNameMap[L'C'] = lpoVecUint;
- loNameMap[L'A'] = lpoVecUint;
- loNameMap[L'B'] = lpoVecUint;</P><P> 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);</P><P> loNameMap[L'C'] = lpoVecUint;
- loNameMap[L'A'] = lpoVecUint;
- loNameMap[L'B'] = lpoVecUint;</P><P> vector<UINT>* p = loNameMap[L'A']; // 测试能否找到
- std::cout<<p->size()<<std::endl;
- return 1;
- }
|
评论暂时关闭