2011-07-31 CPlusPlus0X

Range based for loops

Looping over containers is a very common task so it should be easy two write and easy to read. In C++ is was even worse than in many other languages due to the verbose code for treating iterators. We have seen that the new meaning for the auto keyword has resolved that to some extent. But it gets better.

The new construct for range based for loops makes it even easier. For example: To loop over a list of ints we can write it like this:

list<int> numbers {1, 2, 3, 4, 5};

for (int& i : numbers)
{
   i += 2;
}

This will loop over the list and increment each item by two. Note the very compact and clear notation.

auto works too so you could even write the loop like this:

for (auto & i : numbers)
{
   i += 2;
}