1. 概念
map是一种关联式容器。map中所有元素都会根据元素的键值自动排序。map中所有的元素都是pair,同时拥有key和value。
2. 源码分析
以G2.9为例,以下是map的部分源码实现:
template <class Key,
class T,
class Compare = less<Key>, //缺省采用递增排序
class Alloc = alloc>
class map
{
public:
typedef Key key_type; //键值型别
typedef T data_type; //数据(实值)型别
typedef T mapped_type;
typedef pair<const Key, T> value_type; //元素型别(键值/实值) Key为const,不可修改
typedef Compare key_compare; //键值比较函数
private:
typedef rb_tree<key_type, value_type,
select1st<value_type>, key_compare, Alloc> rep_type; //以红黑树表现map
rep_type t;
public:
typedef typename rep_type::iterator iterator;
...
};
template <class Arg, class Result>
struct unary_function {
typedef Arg argument_type;
typedef Result result_type;
};
//拿第一个元素,即取key
template <class Pair>
struct select1st :
public unary_function<Pair, typename Pair::first_type>
{
const typename Pair::first_type& operator() (const Pair& x) const { //重载"()"操作符
return x.first;
}
};
1) map内部采用的就是一种非常高效的平衡检索二叉树:红黑树,也成为RB树(Red-Black Tree)。RB树的统计性能要好于一般平衡二叉树,所以被STL选择作为了关联容器的内部结构;
2) map的迭代器类型是rep_type::iterator,其值是可以改变的;但又因为typedef pair<const Key, T> value_type中Key值被定义为const类型,故键值是不可修改的;
3) map是通过select1st<value_type>算法获取Key值,基本思想是传入一个pair<first, second>,返回pair的first,即对应的key值;
4) map中的key必须是独一无二的,其insert()调用的是rb_tree的insert_unique();
multimap允许拥有相同的键值,其insert()调用的是rb_tree的insert_equal();
3. 用法总结
可参考http://cplusplus.com/reference/map/map/?kw=map