开发过程中,为了便于查找,有时会用map容器进行键值对(key-value)的存储。在C++中,map的常用功能及注意点记录如下。
map 构造
常用的map构造方式如下:
#include <map>
map<string, int> mapScore;
map 插入元素
insert方式
通过insert可以对map插入元素,主要有以下几种方式:
mapScore.insert(pair<string, int> ("Tom", 99)); //pair
mapScore.insert(map<string,int>::value_type("Amy", 99)); //value_type
mapScore.insert(make_pair("John", 99)); //make_pair
array索引
直接对map进行类似数组的赋值操作也可以完成插入元素:
mapScore["Siri"] = 99; //array index notation
以上两种插入元素的方式不同之处在于:
若键已经存在,则insert的新值将会被忽略;array索引的新值将会覆盖旧值。
用上述的代码为基础,执行下面的代码的结果如注释:
mapScore.insert(make_pair("John", 88)); //仍然是John-99
mapScore["Siri"] = 88; //变为Siri-88
map 查找元素
使用find函数对键进行查找,返回指向键的迭代器,若不存在,则返回map的尾端。
map<string, int>::iterator iter = mapScore.find("Siri");
if(iter != mapScore.end())
{
int SiriScore = iter->second;
}
map 删除元素
键删除
int isDeleted = mapScore.erase("Tom"); //成功返回1,失败返回0
迭代器删除
//利用查找删除指定键
iter = mapScore.find("Amy");
if(iter != mapScore.end())
{
mapScore.erase(iter);
}
//利用迭代器批量删除、清空
mapScore.erase(mapScore.begin(), mapScore.end());
//等价于
mapScore.clear();
map的大小
int nSize = mapScore.size();