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

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

## Recommended Posts

Such as, leaving a function object class to update an std::list of objects, instead of writing an iterator loop and have the objects update themselves or have the app state doing it?

##### Share on other sites
It's not necessary, of course, but some might say it makes the code more readable/self-evident.

It's also a lot quicker to write the code, if you use lambda functors such as those Boost.Lambda provides.

##### Share on other sites
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 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 ;)

• 9
• 23
• 10
• 19