Only a minor improvement:
container.erase(
std::remove(container.begin(), container.end(), value),
container.end()
);
of if you want to use an unary predicate my_predicate
:
container.erase(
std::remove_if(container.begin(), container.end(), my_predicate),
container.end()
);
This has exactly the same performance characteristics (find+erase together will touch all elements as well), but elegantly avoids special cases (!= container.end()
) because it is ranged based.
If you don't care about keeping the vector stable (or sorted!) you can also swap
the found element to the back()
and pop_back()
which will slightly improve the average (but not asymptotic!) runtime.
Not to forget this is also a commonly accepted C++ idiom, so it can be more easily recognized.