当需要erase list里的元素时
代码可写为以下形式,可避免list iterator incrementable
std::list<int> T;
std::list<int>::iterator rpos;
for(rpos=T.begin();rpos!=T.end();)
代码可写为以下形式,可避免list iterator incrementable
std::list<int> T;
std::list<int>::iterator rpos;
for(rpos=T.begin();rpos!=T.end();)
{
rpos = T.erase(rpos);
rpos = T.erase(rpos);
}
其他容器也是差不多的,但是map的有点不同,map的erase不是返回下一个iterator的不过可以如下处理
std::map<,> T;
std::map<,>::iterator rpos;
for(rpos=T.begin();rpos!=T.end();)
{
if(...)
{
T.erase(rpos++);
}
else
{
++rpos;
}
}
std::map<,>::iterator rpos;
for(rpos=T.begin();rpos!=T.end();)
{
if(...)
{
T.erase(rpos++);
}
else
{
++rpos;
}
}
本文介绍在Visual Studio 2005中如何在遍历过程中安全地从STL容器如list和map中删除元素。对于list,可以通过直接使用erase方法并获取新的迭代器来实现。而对于map,虽然erase方法不直接返回迭代器,但可以通过特殊的处理方式来避免ListIteratorNotIncrementable错误。
630

被折叠的 条评论
为什么被折叠?



