c++:map容器中erase()的坑
c++进阶之路
·
1、请看以下代码:
for(auto iter=mapTest.begin();iter!=mapTest.end();++iter)
{
cout<<iter->first<<":"<<iter->second<<endl;
mapTest.erase(iter);
}
可能大多数人认为这一段代码没有问题,其返回的是下一个元素的迭代器
然而,这样会导致程序行为不可知,原因是对于容器来说,如果一个元素已经被删除,那么其对应的迭代器就失效了,不应该再被使用,负责会导致程序无定义的行为。
2、正确的做法:
(1)while循环
std::map<std::string, std::string >::iterator it = mapTest.begin();
while(it != mapTest.end())
{
if(TestVal(it->second))
{
it = mapTest.erase(it);
}
else
it++;
}
(2)for循环
for(auto iter=mapTest.begin();iter!=mapTest.end();) //注意此处不能再写iter++
{
cout<<iter->first<<":"<<iter->second<<endl;
mapTest.erase(iter++);
}
或者采用以下方式:
for (auto it = nodes_.begin(); it != nodes_.end();) {
delete *it;
it = nodes_.erase(it);
}
解读:在这种用法中,该方法中利用了后++的特点,这个时候执行mapTest.erase(it++);这条语句分为三个过程:
1、先把it的值赋值给一个临时变量做为传递给erase的参数变量
2、因为参数处理优先于函数调用,所以接下来执行了it++操作,也就是it现在已经指向了下一个地址。
3、再调用erase函数,释放掉第一步中保存的要删除的it的值的临时变量所指的位置。
更多推荐
已为社区贡献4条内容
所有评论(0)