Erase-remove idiom: what happens when deleting the returned past iterator?

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?

+3
source share
3 answers

I would think that it v.erase(v.end(), v.end())would be well defined and do not erase anything.

+10
source

The C ++ standard states that the member erase(q1,q2)"erases elements in the range [q1, q2]" (see section 23.1.1). Since the range excludes the last element,

v.erase(v.end(), v.end());

valid and does not erase anything.

+10
source

++ Reference:

first , first==last: - -op.

+2

Source: https://habr.com/ru/post/1721949/


All Articles