vector中的元素{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
。
为什么使用下面的方法可以删除vector容器的偶数
for(auto vbegin = va.begin(); vbegin != va.end(); ++vbegin)
{
if(!(*vbegin % 2))
{
va.erase(vbegin);
}
}
而当使用类似的方法删除奇数时会报错代码如下,错误提示:Signal: SIGSEGV (Segmentation fault)
for(auto vbegin = va.begin(); vbegin != va.end(); ++vbegin)
{
if(*vbegin % 2)
{
va.erase(vbegin);
}
}
The solution above assigns the iterator to begin() to achieve the effect, but it will restart the traversal every time, reducing efficiency. And another copy iterator will encounter out-of-bounds problems.
This is my plan:
C++ iterators become invalid after erasure,
so the effect of
va.erase(vbegin);
after++vbegin
is executed is unknown.It is recommended to define a temporary iterator within the if block to delete container elements
Both are wrong, because the iterator will become invalid after the erase call, you need to
Check the information to find out what happened with erase