映射和多重映射基于某一类型Key的键集的存在,提供对T类型的数据进行快速和高效的检索。
对map而言,键只是指存储在容器中的某一成员。
Map不支持副本键,multimap支持副本键。
Map和multimap对象包涵了键和各个键有关的值,键和值的数据类型是不相同的,这与set不同。set中的key和value是Key类型的,而map中的key和value是一个pair结构中的两个分量。
使用map得包含map类所在的头文件:
#include <map> //注意, STL头文件没有扩展名.h
map的构造:
Template<class T1, class T2>
map(); // 默认构造函数
map(const map& m) // 拷贝构造函数
map(iterator begin, iterator end ); //区间构造函数
map(iterator begin, iterator end, const traits& _compare) //带比较谓词的构造函数
map(iterator begin, iterator end, const traits& _compare, const allocator& all) //带分配器
map的基本定义:
map对象是模板类,需要关键字和存储对象两个模板参数:
std:map<int, string> personnel;
这样就定义了一个用int作为索引,并拥有相关联的指向string的指针。
为了使用方便,可以对模板类进行一下类型定义:
typedef map<int, CString> UDT_MAP_INT_CSTRING;
UDT_MAP_INT_CSTRING enumMap;
map<sring,map<string,long> > //注意:最后两个>之间有个空格
map支持下标运算符operator[],用访问普通数组的方式来访问map;不过下标为map的键,在multimap中一个键可以对应多个不同的值。
map的基本用法:
插入、查找、删除、遍历等等
如何实现双键map(可以扩展到多键):
1) 只有两个键都匹配才命中目标;
2) 两个键中任意一个匹配就命中目标。
map的特点:
1) map将Key的object和T的Object绑定到一起, 因此是一种Pair Associative Container, 表示其value type为pair.
2) 它同时也是Unique Associative Container,表示没有两个元素具有相同的Key.
3) 它还是一种Sorted Associative Container,因此第三个参数只能是less, greater之类的functor,相比较而言,hash table是 equal_to、not_equal_to之类的functor。
参考: