概念
Map
是STL
的一个关联容器,它提供一对一(其中第一个可以称为关键字,每个关键字只能在map
中出现一次,第二个可能称为该关键字的值)的数据处理能力,由于这个特性,它完成有可能在我们处理一对一数据的时候,在编程上提供快速通道。
个人理解
map
可以看做一个特殊的数组,其下标可以为任意类型,即key
基本操作
定义
1 | map<Type, Type> dictionary |
常用成员函数
erase
删除指定map
中指定的元素
1 | dictionary.erase("an") //删除键为“an”的元素 |
insert
在map
中添加元素
1 | maplive.insert(pair<int,string>(321,"hai"));//插入一个元素,key为321,value为hai |
find
在map
中查找关键key
,当所查找的关键key
出现时,它返回数据所在对象的位置,如果沒有,返回值与end
函数的值相同1
2
3
4
5
6
7
8
9//在map中寻找key为"123"的元素,并返回其value
map<string, int>::iterator iter = dictionary.find("123");
if(iter != dictionary.end()) {
printf("Find, the value is %d\n", iter->second);
}
else {
printf("Do not Find\n");
}