Q: What is the best way to remove all elements of a particular value from a container?
A: Use the so-called 'remove/erase' idiom:
This is because of the simple fact that 'remove()' is a generic algorithm which takes iterators as its arguments. The iterators know nothing of their container; the STL was designed so as to grant the smallest possible amount of coupling. Thus, the iterators cannot call any container's 'erase()' or similar function.Code:// taken from Item 32 of Scott Myers' Effective STL vector<int> v; v.erase(remove(v.begin(), v.end(), 99), v.end());
'remove()' DOES return the container's new 'end()' (which just
happens to be the first element that was removed) and this value
can be used in the container's 'erase()' call.