The range-based for
loop was introduced in C++11; it provides an intuitive way of iterating through the elements in a collection.
The traditional for loop requires a lot of boilerplate code to implement iteration: a condition needs to be specified along with a variable whose value changes in each iteration.
Here is an example:
#include <iostream>#include <string>using namespace std;int main() {string heroes[3] = {"Batman", "Wonder Woman", "Spiderman"};for(int i = 0; i < 3; i++){cout << heroes[i] << endl;}}
In such a case, the size of the array must be known and there is some indexing involved. Both of these aspects can complicate the process of iteration.
The new range-based for
loop simplifies things. Its structure can be seen below:
All we have to do is specify the collection and an iterator (element
) which has the same type as the collection’s elements. We can name the iterator anything and its type can be handled by auto
.
In each iteration, the iterator will become the next element in the collection. No indexing is involved!
The collection can be any container in the C++ Standard Library.
Let’s apply the range-based for loop onto the previous example:
#include <iostream>#include <string>using namespace std;int main() {string heroes[3] = {"Batman", "Wonder Woman", "Spiderman"};for(auto hero : heroes){cout << hero << endl;}}
Now, we do not need to know the size of the collection(an array in this case). Furthermore, the new iterator (hero
) is more readable than the i
we had earlier.
The iterator is now the actual element rather than an index or a counter.
The range-based for
loop can work in the same way with all other STL containers. Due to the auto
keyword, we do not need to worry about specifying the type of the iterator.