错误的删除方法:
for(vector<int>::iterator it = vecInt.begin(); it != vecInt.end();it++)
{
if( 1)//条件成立
{
vecInt.erase( it );
}
}
使用上面的方法删除元素,程序中会报错:vector iterators incompatible,原因是erase后,it的指向是不定的,不能在用来跟vecInt中的元素做比较,正确的做法是将erase的返回值赋给变量it,erase函数的返回值是指向被删除元素的后继元素或者end.
正确的删除方法:
for(vector<int>::iterator it = vecInt.begin(); it != vecInt.end();)
{
if( 1)//条件成立
{
it = vecInt.erase( it );
}else
{
it ++;
}
}
[积累]正确删除Vector元素的方式
最新推荐文章于 2023-07-24 10:34:54 发布