How can you erase elements from a vector while iterating?

Since C++20, there are freestanding std::erase and std::erase_if functions that work on containers and simplify things considerably:

std::erase(myNumbers, number_in);
// or
std::erase_if(myNumbers, [&](int x) { return x == number_in; });

Prior to C++20, use the erase-remove idiom:

std::vector<int>& vec = myNumbers; // use shorter name
vec.erase(std::remove(vec.begin(), vec.end(), number_in), vec.end());
// or
vec.erase(std::remove_if(vec.begin(), vec.end(), [&](int x) {
    return x == number_in;
}), vec.end());

What happens is that std::remove compacts the elements that differ from the value to be removed (number_in) in the beginning of the vector and returns the iterator to the first element after that range. Then erase removes these elements (whose value is unspecified).

Leave a Comment