missingfaktor missingfaktor - 4 months ago 12
C++ Question

Advantages of std::for_each over for loop

Are there any advantages of

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?

Answer

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 is available in Java and C# for some time now, and there is actually way more foreach loops than classical for loops in every recent Java or C# code I saw.