Range based for loop of C++11 Similar to 'for each'

In my previous articles about C++11 standard I talked about automatic type detection , decltype keyword and uniform initializer list introduced in C++11.

Lets see the Range-based for loop today:

Earlier, the for loop which we use to traverse a list has unnecessary counter increment and check for the last element in the list.

For example:

If I want to print all the elements in an array, then the code will be

    // C++03 code
    int arr[10] = {0,1,2,3,4,5,6,7,8,9};
    for(int cnt=0; cnt < 10; cnt++)
        cout << arr[cnt] << endl;
Languages like java and C# already had for each loop which is easier to use in such cases. the java code will be
    // Java Code
    for(int x : arr)
        System.out.println(x); // similar to cout in C++
C++11 introduces range-based for loop which is similar to for-each loop of other languages. The above code in C++11 will be
    // C++11 Code
    int arr[10] = {0,1,2,3,4,5,6,7,8,9};
    for (int &x : arr)
        cout << x << endl;
Lets look at a more complex problem:
    // Code before C++11
    map another_class_map;
    for (map<myclass, vector>::const_iterator it = another_class_map.begin();
        it != another_class_map.end(); ++it)
    {
        ....
    }
    // C++11 Code
    map<myclass, vector> another_class_map;
    for (auto x : another_class_map)
    {
        ....
    }

0 Comments

Leave a comment