map 是一种关联容器, 提供一对一的关联, 关联的形式为: KEY----VALUE 关键字不重复。multimap与map类似,但是允许关键字重复
即:关键字和与之对应的值
关键字起到索引的作用, 在map中查找记录 就是根据关键字查找
关键字 和 值 可以是任意类型
map 也可看做是 关键字映射的集合, 即,map中不可出现重复的关键字,每条映射的关键字都是不同的。
map 是基于红黑树结构的,其查找时间为LOG(N)
如:
map<int, int > //第一个为关键字,第二个为此关键字所对应的值 一个关键字只对应一个值, 是一对一的映射关系
map<CString,int>
map<int, CString>
map<CString,CString>
........
头文件
1 插入元素
1) insert函数插入
用insert函数插入数据,在数据的插入上涉及到集合的唯一性这个概念,即当map中有这个关键字时,insert操作是插入数据不了的
判断是否插入成功
2 )数组插入方式
用数组方式就不同了,它可以覆盖以前该关键字对应的值
但存在一个性能的问题。该方法会将每个插入值都赋为缺省值,然后再赋为显示的值,如果元素是类对象,则开销比较大。而用insert方法则可直接赋值为显示值。
2 判断是否存在
Returns the number of elements in a map whose key matches a parameter-specified key.
size_type count(
const Key& _Key
) const
|
1 if the map contains an element whose sort key matches the parameter key; 0 if the map does not contain an element with a matching key.
3 查找关键字
iterator find(
const Key& _Key
);
const_iterator find(
const Key& _Key
) const;
|
扩展:
iterator lower_bound(
const Key& _Key
);
const_iterator lower_bound(
const Key& _Key
) const;
|
Returns an iterator to the first element in a map with a key value that is equal to or greater than that of a specified key.
第一个等于或大于Key的元素
iterator upper_bound(
const Key& _Key
);
const_iterator upper_bound(
const Key& _Key
) const;
|
Returns an iterator to the first element in a map that with a key having a value that is greater than that of a specified key.
第一个大于Key的元素
pair <const_iterator, const_iterator> equal_range (
const Key& _Key
) const;
pair <iterator, iterator> equal_range (
const Key& _Key
);
|
A pair of iterators such that the first is the lower_bound of the key and the second is the upper_bound of the key.
Equal_range函数返回一个pair,pair里面第一个变量是Lower_bound返回的迭代器,pair里面第二个迭代器是Upper_bound返回的迭代器,如果这两个迭代器相等的话,则说明map中不出现这个关键字
4 大小,包含多少个元素
Returns the number of elements in the map.
size_type size( ) const; |
5 遍历
前向迭代器
反向迭代器
6 删除
iterator erase(
iterator _Where
);
iterator erase(
iterator _First,
iterator _Last
);
size_type erase(
const key_type& _Key
);
|
7 基本函数
示例:
原文:http://www.cnblogs.com/xzh1993/p/5234326.html