标准std中只有map,是使用平衡二叉树实现的,查找和添加的复杂度都为O(log(n)),
没有提供hash map,gnu c++提供了hash_map,是一个hash map的实现,查找和添加复杂
度均为O(1)。
不过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、
随机数生成器的功能。
没有提供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;
}