一个hash_map的奇怪问题

来源:互联网 发布:网络歌手一般收入多少 编辑:程序博客网 时间:2024/05/30 23:13

            今天,一个朋友问我一个问题,说下面的一段代码不能正常工作:

           

#include <iostream>
#include <hash_map>
#include <map>
using namespace std;
using namespace stdext;

void main()
{
 struct CharCompare
 {
 public:
  bool operator()(const char* _Left, const char* _Right) const
  {
   return (strcmp(_Left, _Right) == 0);

   
  }
 };
 hash_map<const char*, int, hash_compare<const char*, CharCompare> > CharHash;

 CharHash["abc"] = 3;
 CharHash["rew"]  =2;
 cout<<CharHash["abc"]<<endl;
 cout<<CharHash["rew"]<<endl;
}

 

 

 

              这段代码在VS2008下,不能输出预期的结果,其实,VS中的hash_map是这样地定义的:

              template <
   class Key,
   class Type,
   class Traits=hash_compare<Key, less<Key> >,
   class Allocator=allocator<pair <const Key, Type> >
>
class hash_map;

 

 

             为什么那段代码不能正常工作呢?这个要从hash_map的实现原理说起。hash_map工作的时候,其实需要两个函数,一个是哈希函数,一个是比较函数,哈希函数是用来决定要把值放置到哪个桶里的,比较函数则用来在桶里取出对应值。换言之,我们从hash_map中按某个key查询的时候,第一步是先根据哈希函数算出这个key对应的桶,第二步是用比较函数在桶里查找这个key。在第二步的过程中,比较是基于等价的,所谓等价,其实就是关联容器里关于对象的相对位置。在关联容器里,为了确定对象的顺序,需要定义一个比较函数,例如传入两个值a,b,在关联容器里是怎么定义等价的呢?如果a不在b前面,并且b不在a前面,那么a跟b就是等价的,这也是hash_map中判断key是否存在的依据。

 struct CharCompare
 {
 public:
  bool operator()(const char* _Left, const char* _Right) const
  {
   return (strcmp(_Left, _Right) == 0);

   
  }
 };

这段代码其实需要定义的就是这样一个等价函数,一般来说,STL都是基于less检测来实现等价判断的,说都这里,相信大家明白是要怎么处理了吧?没错,就是把 == 改成 <