[Solved] How to use erase-remove idiom and increment an iterator in a loop?


std::remove() simply moves all elements (not one element!) of a specified value to the end of the container, and then returns the new logical past-end iterator. std::remove() does not invalidate iterators, as items are not physically removed and so the container size does not changed. Only the values inside the container are moved around.

After you have “removed” everything you want to remove, you would then call erase() one time at the end to physically remove those items from the container.

Try this:

std::vector<int> vec = { 3, 6, 7, 5 };

auto itr = vec.begin();
auto end = vec.end();

while (itr != end)
{
    end = std::remove(vec.begin(), end, ...);
    ++itr;
}

vec.erase(end, vec.end());

1

solved How to use erase-remove idiom and increment an iterator in a loop?