STL的map里有一个erase方法用来从一个map中删除掉迭代器指示的结点
如
map<string,string> mapTest;
auto it=mapTest.find(key);
mapTest.erase(it);
像上面这样只是删除单个节点,map的行为不会出现任何问题
但是当在一个循环里用的时候,往往会被误用,那是因为使用者没有正确理解iterator的概念
像下面这样的一个例子就是错误的写法
for(auto it=mapTest.begin();it!=mapTest.end();it++){
cout<<it->first<<":"<<it->second<<endl;
mapTest.erase(it);
}
这是一种错误的写法,会导致程序行为不可知。究其原因是map是关联容器,对于关联容器来说,如果某一个元素已经被删除,那么其对应的迭代器就失效了,不应该再被使用,否则会导致程序无定义的行为。
可以用以下方法解决这问题
正确的写法
1、使用删除之前的迭代器定位下一个元素。STL建议的使用方式
for(auto it=mapTest.begin();it!=mapTest.end();){ //注意此处不能再写it++
cout<<it->first<<":"<<it->second<<endl;
mapTest.erase(it++);
}
2、erase() 成员函数返回下一个元素的迭代器
for(auto it=mapTest.begin();it!=mapTest.end();){
cout<<it->first<<":"<<it->second<<endl;
it=mapTest.erase(it);
}
注:auto为C++ 11标准