I got this question when I was reading erase-remove idiom
(item 32) from Scott Meyers "Effective STL” book.
vector<int> v;
...
v.erase(remove(v.begin(), v.end(), 99), v.end());
remove
basically returns the "new logical end” and elements of the original range that start at the "new logical end" of the range and continue until the real end of the range are the elements to be erased from container.
Sounds good. Now, let me ask my question:
In the above example, remove
can return v.end()
if 99 is not found in the vector v
. It is basically passing past-the-end-iterator
to erase method.
- What happens when
past-the-end-iterator
is passed to theerase
method? Does standard says it a UB? - If it is undefined behavior, then
erase-remove idiom
example in Scott Meyer’s book should have looked like:
vector<int> v;
...
vector<int>::iterator newEndIter = remove(v.begin(), v.end(), 99);
if(newEndIter != v.end() )
{
v.erase(newEndIter, v.end();
}
Any ideas on this?