There have been a few questions regarding this issue before; my understanding is that calling std::vector::erase
will only invalidate iterators which are at a p
after erasing an element, is the iterator at that position still valid
No; all of the iterators at or after the iterator(s) passed to erase
are invalidated.
However, erase
returns a new iterator that points to the element immediately after the element(s) that were erased (or to the end if there is no such element). You can use this iterator to resume iteration.
Note that this particular method of removing odd elements is quite inefficient: each time you remove an element, all of the elements after it have to be moved one position to the left in the vector (this is O(n2)). You can accomplish this task much more efficiently using the erase-remove idiom (O(n)). You can create an is_odd
predicate:
bool is_odd(int x) { return (x % 2) == 1; }
Then this can be passed to remove_if
:
vec.erase(std::remove_if(vec.begin(), vec.end(), is_odd), vec.end());
Or:
class CIsOdd
{
public:
bool operator()(const int& x) { return (x % 2) == 1; }
};
vec.erase(std::remove_if(vec.begin(), vec.end(), CIsOdd()), vec.end());