question about the stl erase-remove idiom

N

Nan Li

Hello,
I have seen people doing erase remove idiom like the following:

' vec.erase(remove_if(vec.begin(), vec.end(), is_odd<int>),
vec.end() );'

I remember Scott Meyers also uses this form in his 'Effective
STL' book. ( I cannot verify it right now because the book is not with
me )
But I was wondering if this form is safe, in the strictest sense.
The underlying question is ' does remove guarantee that the end()
iterator is still valid after the operation' ? If it is not guaranteed
and if the second parameter 'vec.end()' is evaluated first (before
remove), then vec.erase will possibly get a new end as the first
parameter, but an old/invalid end() iterator as the second.
I hope I explained my question clearly.

Thanks,
Nan
 
R

Ron Natalie

Nan said:
Hello,
I have seen people doing erase remove idiom like the following:

' vec.erase(remove_if(vec.begin(), vec.end(), is_odd<int>),
vec.end() );'

I remember Scott Meyers also uses this form in his 'Effective
STL' book. ( I cannot verify it right now because the book is not with
me )
But I was wondering if this form is safe, in the strictest sense.
The underlying question is ' does remove guarantee that the end()
iterator is still valid after the operation' ? If it is not guaranteed
and if the second parameter 'vec.end()' is evaluated first (before
remove), then vec.erase will possibly get a new end as the first
parameter, but an old/invalid end() iterator as the second.
I hope I explained my question clearly.

There is no guarantee on the order of execution, but none is required.
The moving around of items in the sequence can't do anything that
would invalidate the end() iterator since it's not evaluated at all
during the execution of remove (it's passed in as an argument).
This is one of the reasons hy remove doesn't actually remove anything.
 
A

Andrew Koenig

Ron Natalie said:
Nan Li wrote:
There is no guarantee on the order of execution, but none is required.
The moving around of items in the sequence can't do anything that
would invalidate the end() iterator since it's not evaluated at all
during the execution of remove (it's passed in as an argument).

This is a good one to remember the next time you're looking for an interview
question :)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,756
Messages
2,569,540
Members
45,025
Latest member
KetoRushACVFitness

Latest Threads

Top