2.1.1 Range-based For Loops

What was the problem

Before C++11, if someone wanted to iterate over a container, he had to construct an iterator, of the correct type with respect to the container, and write the loop with the classical three steps: initialization (get an iterator on the begining of the container), stopping condition (the iterator has not reached the end), and the loop increment.

void multiply(std::vector<int>& v, int c) 
  // I’m going to iterate over v, so I need an iterator. 
  typedef std::vector<int>::iterator it_t; 
  const it_t end(v.end()); 
  for (it_t it(v.begin()); it != end; ++it) 
    *it *= c; 
How the Problem is Solved

All of this was quite verbose and repetitive when using standard containers. Starting from C++11, all this administrative stuff can be avoided by using a ranged-based for loop.

void multiply(std::vector<int>& v, int c) 
  // Just get all entries from v. 
  for (int& vi : v) 
    vi *= c; 

This format uniformizes iteration over anything having a begining and an end. Moreover, it handles the typical subtleties of for loops for you: the end of the container is guaranteed to be computed only once and the increment use the preincrement operator.