Saturday, November 12, 2011

Range based for loop in C++11

Range based for loop allow easy iteration through list of elements. This type of loop will work for C-style arrays, initializer lists and any type that has a begin() and end() function that returns iterators.
In the below example, the range-based for loop will then iterate over every element in this list and increment its value by 2.
int arr[] = {1,2,3,5};
for(auto &i : arr) {
    i += 2;
} 

std::vector<int> myVector (arr, arr+4);
for (auto j: myVector)
   std::cout << j<< std::endl;
To support the range-for loop, the user defined types (classes) must have suitable begin() and end() functions.

No comments:

Post a Comment