---
title: "C++中map和hash_map的区别"
author: "jishublog"
date: "2013-09-22T17:21:00Z"
tags: []
slug: "c-map-hash-map"
draft: false
lastmod: "2013-09-22T19:29:20Z"
id: 1945403
url: "https://jishublog.iteye.com/blog/1945403"
---

# C++中map和hash\_map的区别

> 这里列几个常见问题，应该对你理解和使用hash\_map比较有帮助。

> 1 hash\_map和map的区别在哪里？

> 构造函数。hash\_map需要hash函数，等于函数；map只需要比较函数(小于函数).

> 存储结构。hash\_map采用hash表存储，map一般采用红黑树(RB Tree)实现。因此其内存数据结构是不一样的。

> 2 什么时候需要用hash\_map，什么时候需要用map?

总体来说，hash\_map 查找速度会比map快，而且查找速度基本和数据量大小无关，属于常数级别;而map的查找速度是log(n)级别。并不一定常数就比log(n) 小，hash还有hash函数的耗时，明白了吧，如果你考虑效率，特别是在元素达到一定数量级时，考虑考虑hash\_map。但若你对内存使用特别严格，希望程序尽可能少消耗内存，那么一定要小心，hash\_map可能会让你陷入尴尬，特别是当你的hash\_map对象特别多时，你就更无法控制了，而且hash\_map的构造速度较慢。

> 现在知道如何选择了吗？权衡三个因素: 查找速度, 数据量, 内存使用。

> 这里还有个关于hash\_map和map的小故事，看看:http://dev.csdn.net/Develop/article/14/14019.shtm

> 3 如何在hash\_map中加入自己定义的类型?

你只要做两件事, 定义hash函数，定义等于比较函数。下面的代码是一个例子：

-bash-2.05b$ cat my.cpp  
#include &lt;hash\_map&gt;  
#include &lt;string&gt;  
#include &lt;iostream&gt;

using namespace std;  
//define the class  
class ClassA{  
public:  
ClassA(int a):c\_a(a){}  
int getvalue()const { return c\_a;}  
void setvalue(int a){c\_a=a;}  
private:  
int c\_a;  
};

//1 define the hash function  
struct hash\_A{  
size\_t operator()(const class ClassA & A)const{  
// return hash&lt;int&gt;(classA.getvalue());  
return A.getvalue();  
}  
};

//2 define the equal function  
struct equal\_A{  
bool operator()(const class ClassA & a1, const class ClassA & a2)const{  
return a1.getvalue() == a2.getvalue();  
}  
};

int main()  
{  
hash\_map&lt;ClassA, string, hash\_A, equal\_A&gt; hmap;  
ClassA a1(12);  
hmap\[a1]="I am 12";  
ClassA a2(198877);  
hmap\[a2]="I am 198877";

cout&lt;&lt;hmap\[a1]&lt;&lt;endl;  
cout&lt;&lt;hmap\[a2]&lt;&lt;endl;  
return 0;  
}  
\-bash-2.05b$ make my  
c++ -O -pipe -march=pentiumpro my.cpp -o my  
\-bash-2.05b$ ./my  
I am 12  
I am 198877

> 4如何用hash\_map替换程序中已有的map容器？

这个很容易，但需要你有良好的编程风格。建议你尽量使用typedef来定义你的类型：  
typedef map&lt;Key, Value&gt; KeyMap;  
当你希望使用hash\_map来替换的时候，只需要修改:  
typedef hash\_map&lt;Key, Value&gt; KeyMap;  
其他的基本不变。当然，你需要注意是否有Key类型的hash函数和比较函数。

> 5为什么hash\_map不是标准的？

具体为什么不 是标准的，我也不清楚，有个解释说在STL加入标准C++之时，hash\_map系列当时还没有完全实现，以后应该会成为标准。如果谁知道更合理的解释，也希望告诉我。但我想表达的是，正是因为hash\_map不是标准的，所以许多平台上安装了g++编译器，不一定有hash\_map的实现。我就遇到了这样的例子。因此在使用这些非标准库的时候，一定要事先测试。另外，如果考虑到平台移植，还是少用为佳。

> 6 有学习使用hash\_map的建议吗？

hash中文是哈希，也成为散列，听见别人说散列容器不要埋怨自己孤陋寡闻。了解hash系列，你还可以看看这篇文章:effective STL 25: 熟悉非标准散列容器, 另外建议查看源代码。如果还有问题，那么你可以在STL论坛上提问，会有高手回答你的。