C++11 – Part 3: Range-Based For Loops

A fairly common thing to do with an array or container is to loop over its values. Consider the following loop for loop over a std::vector<int> v:

for(std::vector<int>::const_interator i = v.begin(); i != v.end(); ++i)

Based on what is already covered in this series, we can simplify this statement to:

for(auto i = v.begin(); i != v.end(); ++i)

That is already a big improvement, but there is the tedium of always specifying the begin and end values. This is where the new range-based for loop syntax comes in. The entire expression can be reduced to:

for(auto i : v)

Note that i in this syntax is not the iterator, but the value the iterator points to so there is no need to dereference it in the loop body. All standard loop control such as break and continue can be used as in a traditional loop. If you want to modify the variable (or avoid passing around large data types by value) and the underlying iterator supports it, you should make the loop variable a reference:

for(auto& i : v)

This syntax can be used for arrays and any container from the STL. You can also use it on your own containers provided a few conditions are met. Firstly it must have either both begin() and end() member functions, or have free standing begin() and end() functions that take it as a parameter. These functions need to return an iterator, which by definition is required to implement operator++(), operator!=() and operator*().

Comments are closed.