很容易受数组的影响,写出如下代码:
std::vecotr::iterator it = vc.begin();
for( ; it != vc.end(); it++ )
{
if( ***** ) vc.erase(it);
}
原因是vector中在删除一个元素后,迭代器会自动指向下一个元素。所以,上面的代码很可能导致迭代器越界。《The C++ Standard Library》中解释: c.erase(pos) Removes the element at iterator position pos and returns the position of the next element 所以,正确做法应该是:
for( ; it != vc.end(); )
{
if( ***** )
{
vc.erase(it);
}
else { it++; }
} 问题又来了,上面的代码在C++ Builder 6.0 、Mingw32 2.95下编译运行完全正常,但vc下面同样会出错(Visual Studio 2008),在erase后,it失效,并不是指向vector的下一个元素,it成了一个“野指针”。正确的例子如下
例子: