range based for-loop

In standard C++, iterating over the elements of a container requires a lot of code. Other languages like C# and Java have shortcuts that allow one to write a simple foreach statement that automatically walks the container from start to finish. C++11 has a similar feature. The statement (range-based) for will allow for easy iteration over container of elements:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
#include <vector>

int main()
{

    std::vector<int> vec(10);
	
    //
    //  with range-based for loop
    //
    for( auto& var :  vec)
    {
        std::cout << var << std::endl;
    }
    
    //  with iterators, the old-way
    //
    for( auto iter = vec.begin(), end = vec.end(); iter != end; ++iter)
    {
        std::cout << *iter << std::endl;
    }
    
    return 0;
}

This form of for, called the range-based for, will iterate over each element in the container. It will work for C-style arrays, initializer lists, and any type of container that has a begin() and end() function defined for it that returns iterators. All of the standard library containers that have begin/end pairs will work with the range-based for statement.

Well there is not much to ponder over this feature, except that container should have begin/end function returning iterators to be usable with range-based for loop. This is mostly syntactic sugar, but as sugar it is sweet.