map & hash_map

来源:互联网 发布:java数据库连接池写法 编辑:程序博客网 时间:2024/05/22 01:56

1.map用法

#include <map>

map<string, string> a;

a["a"] = "b";


无类型限制,存储的数据结构为红黑树,因此查找效率为log(n)。



2.hash_map用法

#include<hash_map>

hash_map<int,string> a;

此时默认hash函数和equal_to函数为缺省。

注意:只有key为int等或者char等类型时,可以缺省。其它string或者自定义类,需要自定义hash函数和equal_to函数。

hash函数首选必须定义在一个数据结构里:

struct string_hash{

//然后必须重载operator()函数,且为const函数。

size_t operator () (const string& str ) const{

 return _stl_hash_map(str.c_str()); //必须返回一个size_t(unsigned long int)

}

};


map和hash_map的共同点:

流程上:

先根据key算一个hash值(返回size_t),然后根据该值返回value。


区别:

数据结构:map用红黑树存储;hash_map用哈希表存储。

前者查找的时间为log(n);

后者先根据key和hash函数算出hash值,然后模桶的个数,存放在该桶里;查找时同样先算出在哪个桶,然后用equal_to函数比较该桶中有没有该key的元素。查找时间为O(1)。


区别二:

前者无须定义hash函数和比较函数;后者的缺省只能应对Int(short...)和char(..)类,当string或者自定义类时,需要自定义hash函数和equal_to函数。


3. map的find函数用法

map<int, int> a;

temp = a.find(1); //此时返回类型为一个map<int,int> iterator(指针)

if(temp!=a.end());//找不到时返回a.end()

...

else

cout<<a[1];//找到时,可返回该key的value

cout<<temp->first<<endl;

 cout<<temp->second<<endl;

//注意,因为temp是一个iterator指针,当它是map的指针时,相当于一个struct的指针,key为first member;value为second member。因此也可以通过这个指针来访问找到的key和value


4.hash_map的用法

当key为int和char等时,hash函数和比较函数可以缺省,此时用法和map一样,只是写成hash_map而已。

否则,可参见http://blog.csdn.net/peter_teng/article/details/8433395

原创粉丝点击