Advantages of std::for_each over for loop

std::for_each lambda
std::for_each map
c++ for each array
c for_each vs range-based
std for_each insert
std::find_if
std::transform
std for_each cppreference

Are there any advantages of std::for_each over for loop? To me, std::for_each only seems to hinder the readability of code. Why do then some coding standards recommend its use?

The nice thing with C++11 (previously called C++0x), is that this tiresome debate will be settled.

I mean, no one in their right mind, who wants to iterate over a whole collection, will still use this

for(auto it = collection.begin(); it != collection.end() ; ++it)
{
   foo(*it);
}

Or this

for_each(collection.begin(), collection.end(), [](Element& e)
{
   foo(e);
});

when the range-based for loop syntax is available:

for(Element& e : collection)
{
   foo(e);
}

This kind of syntax has been available in Java and C# for some time now, and actually there are way more foreach loops than classical for loops in every recent Java or C# code I saw.

Is std::for_each obsolete?, languages. However, std::for_each is better and Jon Kalb explains why. Why You Should Use std::for_each over Range-based For Loops. Range based for loop and std::for_each() function in C++11 are fulfilling that need in different situation. These features are tightly coupled with collection type object and mostly used with STL sequential containers, though can be used for user defined class meeting the requirement to be sequential container.

Here are some reasons:

  1. It seems to hinder readability just because you're not used to it and/or not using the right tools around it to make it really easy. (see boost::range and boost::bind/boost::lambda for helpers. Many of these will go into C++0x and make for_each and related functions more useful.)

  2. It allows you to write an algorithm on top of for_each that works with any iterator.

  3. It reduces the chance of stupid typing bugs.

  4. It also opens your mind to the rest of the STL-algorithms, like find_if, sort, replace, etc and these won't look so strange anymore. This can be a huge win.

Update 1:

Most importantly, it helps you go beyond for_each vs. for-loops like that's all there is, and look at the other STL-alogs, like find / sort / partition / copy_replace_if, parallell execution .. or whatever.

A lot of processing can be written very concisely using "the rest" of for_each's siblings, but if all you do is to write a for-loop with various internal logic, then you'll never learn how to use those, and you'll end up inventing the wheel over and over.

And (the soon-to-be available range-style for_each):

for_each(monsters, boost::mem_fn(&Monster::think));

Or with C++x11 lambdas:

for_each(monsters, [](Monster& m) { m.think(); });

is IMO more readable than:

for(Monsters::iterator i = monsters.begin(); i != monsters.end(); ++i) {
    i->think();
} 

Also this (or with lambdas, see others):

for_each(bananas, boost::bind(&Monkey::eat, my_monkey, _1));

Is more concise than:

for(Bananas::iterator i = bananas.begin(); i != bananas.end(); ++i) {
    my_monkey->eat(*i);
} 

Especially if you have several functions to call in order... but maybe that's just me. ;)

Update 2: I've written my own one-liner wrappers of stl-algos that work with ranges instead of pair of iterators. boost::range_ex, once released, will include that and maybe it will be there in C++0x too?

Why You Should Use std::for_each over Range-based For Loops , If execution of a function invoked as part of the algorithm throws an exception and ExecutionPolicy is one of the standard policies, std::terminate is  Questions: This question already has an answer here: Advantages of std::for_each over for loop 19 answers Answers: I think there are some other differences not yet covered by the answers so far. a for_each can accept any appropriate callable object, allowing one to ‘recycle’ the loop body for different for loops.

for_each is more generic. You can use it to iterate over any type of container (by passing in the begin/end iterators). You can potentially swap out containers underneath a function which uses for_each without having to update the iteration code. You need to consider that there are other containers in the world than std::vector and plain old C arrays to see the advantages of for_each.

The major drawback of for_each is that it takes a functor, so the syntax is clunky. This is fixed in C++0x with the introduction of lambdas:

std::vector<int> container;
...
std::for_each(container.begin(), container.end(), [](int& i){
    i+= 10;
});

This will not look weird to you in 3 years.

std::for_each, Are there any advantages of std::for_each over for loop? To me, std::for_each only seems to hinder the readability of code. Why do then some  Ranged for loops. Are the new fancy C++11 range for loops also raw loops? A ranged for loop can be replaced by std::transform or std::for_each. Unlike these algorithms, the for loop is usually only executed over the whole range. The STL algorithms offer more flexibility regarding the start and end.

Personally, any time I'd need to go out of my way to use std::for_each (write special-purpose functors / complicated boost::lambdas), I find BOOST_FOREACH and C++0x's range-based for clearer:

BOOST_FOREACH(Monster* m, monsters) {
     if (m->has_plan()) 
         m->act();
}

vs

std::for_each(monsters.begin(), monsters.end(), 
  if_then(bind(&Monster::has_plan, _1), 
    bind(&Monster::act, _1)));

Foreach loop, Foreach loop (or for each loop) is a control flow statement for traversing items in a collection. Foreach is usually used in place of a standard for loop statement. #​include <iostream> #include <algorithm> // contains std::for_each #include Go'​s foreach loop can be used to loop over an array, slice, string, map, or channel. I'm reading C++ Concurrency in Action by Anthony Williams. In the chapter about designing concurrent code there is parallel version of std::for_each algorihtm. Here is slightly modified code from the

its very subjective, some will say that using for_each will make the code more readable, as it allows to treat different collections with the same conventions. for_each itslef is implemented as a loop

template<class InputIterator, class Function>
  Function for_each(InputIterator first, InputIterator last, Function f)
  {
    for ( ; first!=last; ++first ) f(*first);
    return f;
  }

so its up to you to choose what is right for you.

C++ 11: Range based for loop and std::for_each() function, C++ 11: Range based for loop and std::for_each() function Rvalue References and Perfect Forwarding · C++ 11: Emplacement vs Insertion for STL Containers But there are other scenarios when each one has advantage. If the loop isn't the bottleneck, and the algorithm is simple (like for_each), then for the current C++ standard, I'd prefer a hand-rolled loop for readability. (Locality of logic is key.) However, now that C++0x/C++11 is supported by some major compilers, I'd say use STL algorithms because they now allow lambda expressions — and thus the locality of the logic.

Why You Should Use std::for_each over Range-based For Loops : cpp, Why You Should Use std::for_each over Range-based For Loops This approach is supposed to have advantages over using templates to constrain the​  et enfin, le compilateur pourrait produire un code légèrement meilleur pour std::for_each que pour certains types de fabriqués à la main par la boucle, comme il (for_each) toujours regarde la même chose pour le compilateur, et les rédacteurs de compilateur peut mettre l'ensemble de leurs connaissances, pour le rendre aussi bon que possible.

std::for_each() in C++, Advantages of std::for_each() over for loop. for_each() is more generic. We can use it to iterate over any type of container (by passing the begin  Executes a for loop over a range. Used as a more readable equivalent to the traditional for loop operating over a range of values, such as all elements in a container. The above syntax produces code equivalent to the following ( __range, __begin and __end are for exposition only): range_expression is evaluated to determine the sequence or range

Range-based for loop in C++, It executes a for loop over a range. Used as a more readable equivalent to the traditional for loop operating over a std::vector< int > v = {0, 1, 2, 3, 4, 5}; for_each loop in C++ · Difference between while and do-while loop in C, C++, Java  The closest feature was the general purpose algorithm from the standard library called std::for_each, that applies a function to all the elements in a range. C++11 brought language support for for each that is actually called range-based for loops .

Comments
  • std::for_each when used with boost.lambda or boost.bind can often improve readability
  • The question and accepted answer are from 2010. For a more uptodate answer (from 2018), see here:fluentcpp.com/2018/03/30/is-stdfor_each-obsolete
  • Actually, a foreach loop with scoop has been available for a long time in boost, and I still want to iterate with for_each and a lambda function.
  • The assumption about wanting the entire container range isn't part of the question, so this is only a partial answer.
  • Note that looping over an element is probably not the only thing you want to do, so it can be a good idea to use for_each just so that you learn about find / partition / copy_replace_if and the others, which is what a lot for loops actually do.
  • Range-for is nice, except when you actually need the iterator (then there's no way of getting to it).
  • I'd not use even Element & e as auto & e (or auto const &e) looks better. I'd use Element const e (without reference) when I want implicit conversion, say when the source is a collection of different types, and I want them to convert into Element.
  • +1, several functions or nested types: outer_class::inner_class::iterator or they are template arguments: typename std::vector<T>::iterator... the for construct itself can run into a many line construct in itself
  • (btw: the for_each in the second example is incorrect (should be for_each( bananas.begin(), bananas.end(),...
  • I've written wrappers that use ranges instead of two iterators. These will be available later (see range_ex) but everyone should have them anyway. (Added update on that.)
  • Parallel processing support is no. 1 reason here. We can add implementation to use cuda/gpu for heterogeneous-parallel computing.
  • +1. Ad when for_each takes a container/range instead of two iterators, it's ever more awesome.