Learning New C++ Standards - for loop simplification

| | 1 min read

Usually for loop takes a counter to iterate through the elements. For that you have to initialize a counter, check whether the counter is less than the total element count, then take element from the container and use use it and increment counter.

Eg:


    for (int i = 0; i < myList.size(); ++i)
    {
	     myList[i];

C++ 11 made this thing simpler as follows


    for (int elem : myList)
    {
	    ++elem;

This is called "range-based for" loop. The element type can be reference too. C-style arrays, standard library containers and any containers which has begin(), end() methods which return iterator can be used in this form.