map 经常会被面试问到相关的基本操作;
- 遍历过程删除map的元素是会导致当前绑定到map变量的 iterator 失效,继续使用迭代器会崩溃
- 使用新的缓存map , 复制原来的map,跳过需要删除的那个
- 正常情况下使用 map 的 erase(【下标key】) 删除,或者
- 添加元素,使用类似数组的方式,或者使用 insert(std::make_pair(key, val))
#ifndef CPPLEAR_H
#define CPPLEAR_H
#include <map>
using namespace std;
class Cpplear
{
public:
Cpplear();
void testMap();
// template <class 类型参数1, class类型参数2, ...>
// 返回值类型 模板名(形参表)
// {
// 函数体
// }
template <class Tkey, class Tval>
void printMap(std::map<Tkey, Tval> mapInput) ;
};
#endif // CPPLEAR_H
#include "cpplear.h"
#include <iostream>
#include <QDebug>
Cpplear::Cpplear()
{
}
void Cpplear::testMap()
{
std::map<string, int> mapAge;
mapAge["Mike"] = 17; // 初始化map节点
mapAge["Lucy"] = 20;
mapAge["Jane"] = 18;
mapAge["kaite"] = 16;
mapAge.insert(std::make_pair("aaa", 12)); // 插入一个节点元素
printMap(mapAge);
mapAge.erase("Jane");
std::map<int, int> mapId;
mapId.insert(std::make_pair(0, 99));
mapId.insert(std::make_pair(1, 100));
printMap(mapId);
// 循环中删除一个元素
std::map<string, int> mapAgeNew; // 准备一个缓存map
std::map<string, int>::iterator it = mapAge.begin();
while (it != mapAge.end()) {
cout << it->first << ",age=" << it->second << endl;
if(it->first == "Lucy") { // OK
it++;
continue;
}
mapAgeNew[it->first] = it->second;
it++;
}
qDebug() << "delete one note" ;
printMap(mapAgeNew);
// auto 关键字遍历,按照下标顺序输出
for (auto it: mapAge) {
std::cout << it.first <<"," << it.second << std::endl;
if (it.first == "Mike") {
// mapAge.erase(it.first); // NG, 崩溃
}
}
}
template<class Tkey, class Tval>
void Cpplear::printMap(std::map<Tkey, Tval> mapInput)
{
std::cout << "**************** result ****************" <<std::endl;
// 迭代器遍历
// std::map<Tkey, Tval>::iterator it = mapInput.begin();
// while (it != mapInput.end()) {
// cout << it->first << ",age=" << it->second << endl;
// it++;
// }
// auto 关键字遍历,按照下标顺序输出
for (auto it: mapInput) {
std::cout << it.first <<"," << it.second << std::endl;
}
}