I had this question when I read erase-remove idiom(paragraph 32) from Scott Meyers ' book Effective STL .
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 begin with the “new logical end” of the range and continue until the real end of the range is destroyed from the container.
That sounds good. Now let me ask my question:
In the above example, it removecan return v.end()if 99 is not found in vector v. This is basically a transition past-the-end-iteratorto the erase method.
- What happens when
past-the-end-iteratorpassed to a method erase? Is it a UB standard? - If this behavior is undefined, then the example
erase-remove idiomin Scott Meyers book should look like this:
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?
source
share