---
title: "C++中的hash Map"
author: "fuliang"
date: "2010-07-30T09:53:20Z"
tags: ["C", "C#", "C++", "正则表达式"]
categories: ["编程语言"]
slug: "c-hash-map"
draft: false
lastmod: "2010-07-30T09:53:20Z"
id: 725055
url: "https://fuliang.iteye.com/blog/725055"
---

标准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&gt; months; months\["january"] = 31; months\["february"] = 28; months\["march"] = 31; cout &lt;&lt; "march -&gt; " &lt;&lt; months\["march"] &lt;&lt; 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 &lt;&lt; it-&gt;first &lt;&lt; "-&gt; " &lt;&lt; it-&gt;second &lt;&lt; endl; } return 0; } \[/code]