Should I store the returned iterator when removing from a vector?

I know there's a remove-erase idiom to remove all occurrences of a value in a vector, but I'm using this option instead:
(let's say this is a vector of type int)

1
2
3
4
5
6
    auto i = v.begin();
    while (i!=v.end())
        if (*i==elementToBeRemoved)
            i=v.erase(i);
        else
            i++;


But I'm not quite sure why the i=v.erase(i) part needs the iterator to be reassigned after erasing. I know it's because the iterator is invalidated after calling erase, but I tried the same code without assigning the return value to the iterator (only the v.erase(i) part) and it also works. So why exactly is it that I need to store that returned iterator?

Thanks.
> I tried the same code without assigning the return value to the iterator (only the v.erase(i) part) and it also works.

Though in many cases, this would work for a vector, technically it engenders undefined behaviour for the reasons that you have already stated.

For example, with the Microsoft compiler, when checked iterators are enabled (enabled by default in debug builds), while( i != vec.end() ) would generate an assertion failure if i is an iterator that was invalidated by erase(i).
Thanks for your explanation :)
Topic archived. No new replies allowed.