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
- map & hash_map
- STL:map与hash_map
- std::map & std::hash_map
- hash_map map 比较
- hash_map与map
- 【STL】 map、hash_map、迭代器
- Map与Hash_map
- Map与Hash_Map
- STL map 和 hash_map
- map、hash_map、迭代器
- map与hash_map
- hash_map和map
- hash_map 与map 区别
- hash_map和map
- hash_map 与map介绍
- map hash_map介绍
- map与hash_map
- map, hash_map,unordered_map介绍
- 数据缓存cache中
- 单纯型法Ⅱ(bzoj 1061: [Noi2008]志愿者招募)
- mybatis 第二篇 一些 mybatis 语句
- UTF-8编码占几个字节
- XCode9的新变化
- map & hash_map
- 肾8出来了——谈谈你和苹果的故事
- 出栈全排列
- iOS runtime ~ 重要类型
- Android AndroidManifest 清单文件以及权限详解
- 51Nod 1487 思维+线段树
- js学习-对象
- 46.ClassTag 、Manifest、ClassManifest、TypeTag代码实战及其在Spark中的应用源码解析
- HDU1251:统计难题