Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to erase from vector in range-based loop?

Tags:

c++11

vector

I simply wanna erase the specified element in the range-based loop:

vector<int> vec = { 3, 4, 5, 6, 7, 8 };
for (auto & i:vec)
{
    if (i>5)
    vec.erase(&i);
}

what's wrong?

like image 362
Mostafa Bahri Avatar asked Jul 09 '15 23:07

Mostafa Bahri


1 Answers

You can't erase elements by value on a std::vector, and since range-based loop expose directly values your code doesn't make sense (vec.erase(&i)).

The main problem is that a std::vector invalidates its iterators when you erase an element.

So since the range-based loop is basically implemented as

auto begin = vec.begin();
auto end = vec.end()
for (auto it = begin; it != end; ++it) {
  ..
}

Then erasing a value would invalidate it and break the successive iterations.

If you really want to remove an element while iterating you must take care of updating the iterator correctly:

for (auto it = vec.begin(); it != vec.end(); /* NOTHING */)
{
  if ((*it) > 5)
    it = vec.erase(it);
  else
    ++it;
}  
like image 92
Jack Avatar answered Sep 18 '22 13:09

Jack