Monday, April 8, 2013

C++ 11 : Range-based for loop

C++ 11 has a new feature included in it i.e.; Range-based For loop. You might be wondering about what is range-based for loop. So, it is similar to the standard c++ for loop, or you can also say that it is the brother of foreach, which executes the statement repeatedly and sequentially for each element in the expression.

Syntax:-

for(for-range-declaration : expression)
     statement

Let see an example on this:-

#include <iostream>

using namespace std;

int main()
{
     int x[10] = {1,2,3,4,5,6,7,8,9,10};
     for(auto &i : x) // Access by using reference of the variable
     {
            cout<<i<<endl;
     }
      return 0;
}

It will iterate through all over the array and show the output. You can use it in all C++ STL classes.
For example:-

int main()
{
     vector<int> vec;
     vec.push_back(10);
     vec.push_back(20);
     vec.push_back(30);

      for(auto i : vec) //  Access by using copy of the variable
            cout<<i<<endl;
      return 0;
}

The above code print all the contents in the vector vec.
 A range based for loop terminates when one of these statement executes: a break, a goto, or a  return. A continue statement in the range based for loop terminates only the current iteration.

No comments:

Post a Comment