容器删除的注意事项

对于list等容器再删除时最好使用如下方法:

好方法: 以后LIST 删除使用该方法。防止在VS2005中抛异常

std::list<int> T;
std::list<int>::iterator rpos;
for(rpos=T.begin();rpos!=T.end();)
rpos = T.erase(rpos); 

坏方法:该方法在2005中,有时候会异常。

 T::iterator it=_T.begin();

 for (it=_T.begin(); it!=_T.end(); it++)
 {

  _T.erase(it);

 }

后者一般会报 Iterator Not Incrementable
其他容器也是差不多的,但是map的有点不同,stlport中map的erase不是返回下一个iterator的不过可以如下处理
map::list<,> T;
map::list<,>::iterator rpos;
for(rpos=T.begin();rpos!=T.end();)
{
    if(...)
   {
        T.erase(rpos++);
    }
    else
   {
      ++rpos;
   }
}

 

你可能感兴趣的:(容器删除的注意事项)