在C++语言中,我们经常使用到map集合来存储 key-value 类型的数据。这里将常用到的map集合操作方法整理出来。
1. map集合的初始化
这里列举三种初始化的方法:
//初始化不设置参数
map<string, string> tempMap1;
//初始化设置参数
map<string, string> tempMap2 = { {"1" , "temp21"},{"2" , "temp22"} };
//初始化设置参数 使用 pair 函数指定存储的数据类型
map<string, string> tempMap3 = { pair<string, string>("1" , "temp21"), pair<string, string>("2","temp22")};
2. map集合添加数据
使用 insert() 函数向map集合中添加相应的数据
//直接添加数据 - 添加单个数据
tempMap1["1"] = "数据1";
//添加多个数据 - 添加单个数据
tempMap1.insert({ {"2","数据2"},{"3","数据3"} });
//使用 pari 函数指定存储的数据类型
tempMap1.insert(pair<string, string>("4", "数据4"));
3. map集合的遍历
使用迭代器 iterator 进行map集合的遍历