C++中的hash Map

标准std中只有map,是使用平衡二叉树实现的,查找和添加的复杂度都为O(log(n)),
没有提供hash map,gnu c++提供了hash_map,是一个hash map的实现,查找和添加复杂
度均为O(1)。

#include <ext/hash_map>
#include <iostream>
#include <cstring>

using namespace std;
using namespace __gnu_cxx;

struct eqstr{
bool operator()(const char *s1, const char *s2)const{
return strcmp(s1,s2) == 0;
}
};

int main(){
hash_map<const char *,int,hash<const char *>,eqstr> months;
months["january"] = 31;
months["february"] = 28;
months["march"] = 31;
cout << "march -> " << months["march"] << endl;
}

不过gnu hash_map和c++ stl的api不兼容,c++ tr1(C++ Technical Report
1)作为标准的扩展,实现了hash map,提供了和stl兼容一致的api,称为unorder_map.在头文件
<tr1/unordered_map>中。另外c++ tr1还提供了正则表达式、智能指针、hash table、
随机数生成器的功能。

#include <iostream>
#include <string>
#include <tr1/unordered_map>
using namespace std;

int main(){
typedef std::tr1::unordered_map<int,string> hash_map;
hash_map hm;
hm.insert(std::pair<int,std::string>(0,"Hello"));
hm[1] = "World";
for(hash_map::const_iterator it = hm.begin(); it != hm.end(); ++it){
cout << it->first << "-> " << it->second << endl;
}
return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值