Search code examples
c++vectoriteratorerase

c++ vector erase advances iterator


The following simplified code works, in that it deletes all vector elements. However, I do not understand why. Since f.erase(r) does not capture the returned value which would be the new iterator value, and there is no other iterator incrementor, and according to documentation, erase(iterator position) argument is not passed by reference, where does the iterator get advanced?

#include <iostream>
#include <vector>

int main ()
{
  std::vector<int> f = {1,2,3,4,5};
  auto r = f.begin();
  while (r != f.end())
  {
    std::cout << "Erasing " << *r << std::endl;
    f.erase(r);
  }
  return 0;
}

Solution

  • where does the iterator get advanced?

    It doesn't, the iterator stays pointing to the same location. This is technically undefined behavior but if you think about what the loop is actually doing, you'll see why you get the "correct" results.

    Your vector holds a pointer to the objects that it stores. Your iterator is going to point to that memory with the offset to the element you want. In this case it is going to point to the beginning of the data. When you erase the first element, the iterator is invalidated but it is still pointing to the beginning of the vector. erase moves all of the elements forward so when you go into the next iteration, your in the same state that you were in the first iteration except the vector is one element smaller. You repeatedly do this until there are no elements left and end() == begin()

    You should not depend on this always happening though and instead just use clear() to remove all of the elements from the vector.