Range-based for loop in C++11

In this chapter, you will learn about the new looping essence of Standard C++11. This feature was not available in previous versions of C ++, but with the refinement and inclusion of this new feature, programming using C ++ has become very easy and professional.

C++11 bring in a new kind of for loop that iterates over all elements of a given range/set of arrays or collection. This is what in some other programming languages like C# and would be termed as a foreach and Enhanced For loop respectively.

The basic syntax is as follows:

for ( decllaration : coll/array_name )
{
// statement(s) block;
}

Here, 'declaration' is the statement-section of each element of the passed collection 'coll' or array values and for which the statements specified gets called. Another code snippet shows the following calls for every value of the passed initializer list that writes it on a line to the standard output - cout. Here the example goes -

for ( int i : { 2, 4, 6, 8, 10, 12, 14, 16 } )
{
std:: cout << "The Value :" << i << std:: endl;
}

Another example showing its use with vector, wherein multiplying every element 'elemt' of any vector 'vect' by 3 you can program this as given below:

std:: vector<double> vect;
. . . .
for ( auto& elemt : vect )
{
elemt *= 3;
}

In general, a range-based for loop declared as

for ( decl : coll ) {
statement
}

is equivalent to what is happening in the background when coll provides begin() and end() members along with a starting and existing variable.:

{
for (auto start=coll.begin(), exit=coll.end(); start != exit; ++start ) {
decl = *start;
// statement(s) block;
}
}