Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is the range-based loop different to a for-each loop?

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.

like image 427
charisis Avatar asked Apr 17 '12 11:04

charisis


People also ask

What is the difference between for range loop and?

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.

What is a range-based for loop?

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() .

What is the difference between for loop and for each loop in VB net?

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.


1 Answers

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:

  • The range-based for-loop syntax is cleaner and more universal, but you can't execute the code in loop for a specified range different than from begin() to end().
  • Range-based for-loop can be applied to containers which don't have iterators defined, by defining 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.

like image 61
Rafał Rawicki Avatar answered Sep 28 '22 11:09

Rafał Rawicki