map 和 unordered_map以char * 为key

map unordered_mapchar *key

 

使用map或者unordered_map进行字符串查找一般都是用std::string类型作为key,但是std::string的效率实在太低,不得不进行优化,尝试使用char*key来查找。

 

一、mapchar*key

默认的map<char *,int>key是指针,比较的是指针值的大小,不能进行字符串的匹配。

查看map的模板定义:http://www.cplusplus.com/reference/map/map/?kw=map

template < class Key,                                     //map::key_type

          class T,                                       //map::mapped_type

          class Compare = less<Key>,                     // map::key_compare

          class Alloc = allocator<pair<const Key,T> >    // map::allocator_type

          > class map;

 

因此我们可以编写字符串的比较类来实现map以char *为key,代码如下:

 

 

struct Cmp

{

//重载运算符

bool operator()(const char * str1,constchar * str2)

{

return strcmp(str1,str2) < 0;

}

}

 

map<char*,int,Cmp> mapStr;

mapStr中插入char *就可以进行字符串的查找操作了;

切记,如果是局部指针变量,可能会出现随机结果,因此建议使用char *ss = new char[N],通过new来进行指针的空间申请。

 

二、unordered_mapchar *key

 

unordered_mapC++11中的hash表,因为hash_map已经存在,因此搞了个怪名字。

unordered_map模板定义

http://www.cplusplus.com/reference/unordered_map/unordered_map/?kw=unordered_map):

 

 

 

 

template < class Key,                                    // unordered_map::key_type
           class T,                                      // unordered_map::mapped_type
           class Hash = hash<Key>,                       // unordered_map::hasher
           class Pred = equal_to<Key>,                   // unordered_map::key_equal
           class Alloc = allocator< pair<const Key,T> >  // unordered_map::allocator_type
           > class unordered_map;

 

unordered_map需要重新写hash函数和比较函数,代码如下:

 

//hash函数

struct Hash_Func

{

//BKDR hash algorithm,有关字符串hash函数,可以去找找资料看看

int operator()(PSA_CHAR * str)const

{

int seed = 131;//31  131 1313 13131131313 etc//

int hash = 0;

while(*str)

{

hash = (hash * seed) + (*str);

str ++;

}

 

return hash & (0x7FFFFFFF);

}

};

 

 

//比较函数

struct Cmp

{

bool operator()(const PSA_CHAR *str1,const PSA_CHAR * str2)const

{

return strcmp(str1,str2) == 0;

}

};

 

 

unordered_map<char*,int, Hash_Func ,Cmp> hashStr;

 

编译unordered_map是需要加上编译选项 –std=c++0x

重写hash函数和比较函数的目的应该是只有hash值相同并且字符串也相同才能判断两个字符串是一样的,如果只是hash值相同并不能判断字符串相同。

切记:一定要注意局部指针变量的问题,使用new运算符对指针申请空间,在使用结束遍历map或者unordered_map释放空间。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值