STL之hash_map

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;
         
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值