Sign in to follow this  

Is it unneccesary to replace most container-loops with std::for_each?

This topic is 4351 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I wouldn't move the body of a for-loop into a function or functor solely for the purpose of replacing the for-loop with for_each(), but it seems like a good idea to replace
    for ( iterator i = c.begin(); i != c.end(); ++i )
{
foo( *i );
}
with
    for_each( c.begin(), c.end(), foo ); 
since that is exactly what for_each() does.

Share this post


Link to post
Share on other sites
Right. If you already have a function for it, then use that, but otherwise it's not a hugely useful refactoring most of the time.

On the other hand, you should probably use the erase-remove idiom (with std::remove or std::remove_if) if you need that functionality, rather than trying to mess around with individual element erasures - since apparently everyone gets it wrong most of the time, and it's therefore such a popular topic around here ;)

Share this post


Link to post
Share on other sites

This topic is 4351 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this