Visual Studio中的hash_map

hash_map的声明如下:

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

第四个参数表示map中元素存储的方式,一般情况下,我们都使用pair类型,所以第四个参数使用默认的就可以了。

第三个参数是一个仿函数类,提供两个函数,第一个计算hash,第二个比较key的大小,故要求key支持operator<:

//计算hash值
size_t operator()(const _Kty& _Keyval) const
//比较两个大小
bool operator()(const _Kty& _Keyval1, const _Kty& _Keyval2) const

如果key是int double等基本类型,可以使用默认参数,注意,对string这样的类类型也可以使用这个默认参数(因为1.hash_compare提供了计算string的hash的函数。2.string有<操作符,所以hash_compare可以提供hash和compare的功能)。

hash_map< string, vector<string> > a;

不过,曾经VC(如VC7)是不能这样的,当时,VC STL的作者给了个回答以及解决办法,如下:

The   V7   version   of   hash_map   has   no   default   hash   function   for   strings. 
We 've   already   fixed   this   oversight   --   it   will   appear   in   a   future 
VC++   release.   For   now,   you   can   add   your   own   comparator   along   the 
lines   shown   below: 

struct   mycomp 
  {   //   define   hash   function   for   strings 
  enum 
    {   //   parameters   for   hash   table 
    bucket_size   =   4,   //   0   <   bucket_size 
    min_buckets   =   8};   //   min_buckets   =   2   ^^   N,   0   <   N 

  size_t   operator()(const   string&   s1)   const 
    {   //   hash   string   s1   to   size_t   value 
    const   unsigned   char   *p   =   (const   unsigned   char   *)s1.c_str(); 
    size_t   hashval   =   0; 

    for   (size_t   n   =   s1.size();   0   <   n;   --n) 
      hashval   +=   *p++;   //   or   whatever 
    return   (hashval); 
    } 

  bool   operator()(const   string   &s1,   const   string   &s2)   const 
    {   //   test   if   s1   ordered   before   s2 
    return   (s1   <   s2); 
    } 
  }; 

To use it:

hash_map <string,   int,   mycomp>   mymap; 

HTH, 

P.J.   Plauger 
Dinkumware,   Ltd. 

如果key是自定义的类,就需要像上面那样自己写个仿函数类作为第三个参数了,同时自定义的类应该支持operator<。

 

参考文献:http://www.cppblog.com/guojingjia2006/archive/2008/01/12/41037.aspx

posted @ 2012-09-19 15:57  igody  阅读(676)  评论(0编辑  收藏  举报