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
What are loops and how we can use them?
ReplyDeleteIn 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