这里列几个常见问题,应该对你理解和使用hash_map比较有帮助。
- 构造函数。hash_map需要hash函数,等于函数;map只需要比较函数(小于函数).
- 存储结构。hash_map采用hash表存储,map一般采用红黑树(RB Tree)实现。因此其memory数据结构是不一样的。
4.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
你只要做两件事, 定义hash函数,定义等于比较函数。下面的代码是一个例子:
#include <hash_map>
#include <string>
#include <iostream>
using namespace std;
//define the class
class ClassA{
};
//1 define the hash function
struct hash_A{
};
//2 define the equal function
struct equal_A{
};
int main()
{
}
I am 12
I am 198877