Friday, September 21, 2012

Range-based For Loops in Visual Studio 2012

C++ 11 added a feature for easy iteration over a list of elements which is called range-based for:
int simpleArray[5] = {1, 2, 3, 4, 5};
for (int x : simpleArray)
{
    cout << x;
}
This is similar to 'foreach' statement in other languages. GCC added support of this feature in version 4.6 and now Microsoft added support in Visual Studio 2012 and in Visual C++ 11.

It is possible to modify contents of container making loop variable a reference:
vector<double> v;
v.push_back(1.0);
v.push_back(1.5);
v.push_back(2.0);

for (double &y : v)
{
    y *= 2;
}
Range-based for loop will work automatically with array or with std::vector or other STL containers. You can also make your own data structures iterable in the new way, you can find exact requirements and example of such a class here:

http://www.cprogramming.com/c++11/c++11-ranged-for-loop.html

1 comment:

  1. What are loops and how we can use them?

    In general a loop is a sequence of statements which is specified once but which may be carried out several times in succession. The function of the loop is to repeat the calculation a given number of times until it reaches a certain value. The code inside the loop is obeyed a specified number of times, or once for each of a collection of items, or until some condition is met, or indefinitely. We can divide loops into:
    1) Count-controlled loops,
    2) Condition – controlled loops,
    3) Collection - controlled loops,
    4) General iteration,
    5) Infinite loops,
    6) Continuation with the next iteration,
    7) Redo the current interation and
    8) Restart loop

    For more information please visit: http://megacplusplustutorials.blogspot.com

    ReplyDelete