missingfaktor missingfaktor - 1 year ago 60
C++ Question

Advantages of std::for_each over for loop

Are there any advantages of

loop? To me,
only seems to hinder the readability of code. Why do then some coding standards recommend its use?

Answer Source

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)

Or this :

for_each(collection.begin(), collection.end(), [](Element& e)

when the range-based for-loop syntax is available:

for(Element& e : collection)

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.