向量擦除迭代器

2021-12-21 00:00:00 iterator vector c++

我有这个代码:

int main()
{
    vector<int> res;
    res.push_back(1);
    vector<int>::iterator it = res.begin();
    for( ; it != res.end(); it++)
    {
        it = res.erase(it);
        //if(it == res.end())
        //  return 0;
    }
}

一个随机访问迭代器,指向被函数调用擦除的最后一个元素之后的元素的新位置,如果操作擦除了序列中的最后一个元素,则为向量结束."

"A random access iterator pointing to the new location of the element that followed the last element erased by the function call, which is the vector end if the operation erased the last element in the sequence."

这段代码崩溃了,但是如果我使用 if(it == res.end()) 部分然后返回,它就可以工作.怎么来的?for 循环是否缓存了 res.end() 以便不等运算符失败?

This code crashes, but if I use the if(it == res.end()) portion and then return, it works. How come? Does the for loop cache the res.end() so the not equal operator fails?

推荐答案

res.erase(it) 总是返回下一个有效的迭代器,如果你擦除最后一个元素,它将指向 .end()

res.erase(it) always returns the next valid iterator, if you erase the last element it will point to .end()

在循环结束时 ++it 总是被调用,所以你增加了 .end() 这是不允许的.

At the end of the loop ++it is always called, so you increment .end() which is not allowed.

简单地检查 .end() 仍然会留下一个错误,因为你总是在每次迭代时跳过一个元素(it 通过从 .erase(),然后再次循环)

Simply checking for .end() still leaves a bug though, as you always skip an element on every iteration (it gets 'incremented' by the return from .erase(), and then again by the loop)

你可能想要这样的东西:

You probably want something like:

 while (it != res.end()) {
        it = res.erase(it);    
 }

擦除每个元素

(为了完整性:我假设这是一个简化的例子,如果你只是想让每个元素都消失而不必对其执行操作(例如删除),你应该简单地调用 res.clear())

(for completeness: I assume this is a simplified example, if you simply want every element gone without having to perform an operation on it (e.g. delete) you should simply call res.clear())

当你只是有条件地擦除元素时,你可能想要像

When you only conditionally erase elements, you probably want something like

for ( ; it != res.end(); ) {
  if (condition) {
    it = res.erase(it);
  } else {
    ++it;
  }
}

相关文章