ITeye博客

C++中的hash Map

fuliang · 2010-07-30 09:53 · C/C++ · 编程语言 · C · C++ · 正则表达式 · C# · Markdown

标准std中只有map,是使用平衡二叉树实现的,查找和添加的复杂度都为O(log(n)), 没有提供hash map,gnu c++提供了hash_map,是一个hash map的实现,查找和添加复杂 度均为O(1)。 [code="cpp"] #include #include #include 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,eqstr> months; months["january"] = 31; months["february"] = 28; months["march"] = 31; cout << "march -> " << months["march"] << endl; } [/code] 不过gnu hash_map和c++ stl的api不兼容,c++ tr1(C++ Technical Report 1)作为标准的扩展,实现了hash map,提供了和stl兼容一致的api,称为unorder_map.在头文件 中。另外c++ tr1还提供了正则表达式、智能指针、hash table、 随机数生成器的功能。 [code="cpp"] #include #include #include using namespace std; int main(){ typedef std::tr1::unordered_map hash_map; hash_map hm; hm.insert(std::pair(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; } [/code]

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。