hash_map简介(下列在VS2010下测试)
hash_map的用法和map是一样的,提供了insert,size,count等操作,并且里面的元素也是以pair类型来存贮的。虽然对外部提供的函数和数据类型是一致的,但是其底层实现是完全不同的,map底层的数据结构是rb_tree而,hansh_map却是哈希表来实现的。
总体来说,hash_map 查找速度会比map快,而且查找速度基本和数据量大小无关,属于常数级别;而map的查找速度是log(n)级别。hash还有hash函数的耗时。当有100w条记录的时候,map也只需要20次的比较,200w也只需要21次的比较!所以并不一定常数就比log(n)小!
hash_map对空间的要求要比map高很多,所以是以空间换时间的方法,而且,对应hash_map,如果hash函数和hash因子选择不好的话,也许不会达到你要的效果,所以至于用map,还是hash_map,从3个方面来权衡:查找速度,数据量,内存使用,还有一个就是你的经验!没有特别的标准。
hash_map类在头文件hash_map中,和所有其它的C++标准库一样,头文件没有扩展名。如下声明:
#include <hash_map>
using namespace std;
using namespace stdext;
hash_map是一个聚合类,它继承自_Hash类,包括一个vector,一个list和一个pair,其中vector用于保存桶,list用于进行冲突处理,pair用于保存key->value结构,简要地伪码如下:
class hash_map<class _Tkey, class _Tval>
{
private:
typedef pair<_Tkey, _Tval> hash_pair;
typedef list<hash_pair> hash_list;
typedef vector<hash_list> hash_table;
};
另外可以通过重写 hash_compair仿函数,更改里面关于桶数量的定义,如果取值合适,也可以得到更优的性能。而且如果你的数据是自定义的类型,必须要重写这个仿函数。可以模仿原来的写法,所有的成员函数,成员变量一个不能少!
简单的一个列子,其使用方法和map是一样的:
#include <iostream>
#include <hash_map>
#include <string>
using namespace std;
int main()
{
hash_map<int,string>hmap;//定义一个实例
hmap.insert(pair<int,string>(10,"hashMap"));//插入一个pair对象
hmap.insert(hash_map<int,string>::value_type(34,"test"));//value_type就是pair类型的
hmap[23] = "23";
hmap[33] = "33";
hmap[-1] = "-1";
cout<<"begin-->end:"<<endl;
hash_map<int,string>::iteratorit = hmap.begin();
while(it!=hmap.end())//遍历
{
cout<<it->first<<"\t"<<it->second<<endl;
it++;
}
cout<<"find:"<<endl;
it = hmap.find(-1);// 查找
if(it!=hmap.end())
{
cout<<it->first<<"\t"<<it->second<<endl;
it++;
}
cout<<"size:"<<endl;
cout<<hmap.size()<<endl;