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.
The "for" loop For loops can iterate over a sequence of numbers using the "range" and "xrange" functions. The difference between range and xrange is that the range function returns a new list with numbers of that specified range, whereas xrange returns an iterator, which is more efficient.
Remarks. Use the range-based for statement to construct loops that must execute through a range, which is defined as anything that you can iterate through—for example, std::vector , or any other C++ Standard Library sequence whose range is defined by a begin() and end() .
for Loop vs foreach LoopThe for loop is a control structure for specifying iteration that allows code to be repeatedly executed. The foreach loop is a control structure for traversing items in an array or a collection. A for loop can be used to retrieve a particular set of elements.
Syntax:
for ( range_declaration : range_expression) loop_statement
produces code equivalent to:
{
auto && __range = range_expression ;
auto __begin = begin_expr(__range);
auto __end = end_expr(__range);
for (;__begin != __end; ++__begin) {
range_declaration = *__begin;
loop_statement
}
}
While the std::for_each
applies unary function to the specified range. So, there are two basic differences:
begin()
to end()
.begin()
and end()
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With