The latest C++ 11 specification defines a new type of for loop called “range-based for loop”.
Its looks and mechanics appear to be pretty much identical to the for-each loops available in other languages.
What are the differences between the two of them, if any? If there are no differences why the new name?
Edit: To clarify, I’m not looking for implementation differences between the “range based for” of c++ and other languages’ for each or std::for_each. Instead I was wondering if there was some hidden value behind the fact that they decided to call this new c++ “feature” (or syntax, or idiom or whatever you want to call it) “range-based for loop” instead of “for each loop” as pretty much anyone else seems to be calling these things.
Syntax:
produces code equivalent to:
While the
std::for_eachapplies unary function to the specified range. So, there are two basic differences:begin()toend().begin()andend()functions.You cannot compare it to the “generalized for-each idiom”, because there is no standard idiom. To compare, you have to point out the concrete implementation and the difference is usually hidden in the details.