Range-based for

With C++11 we got a new way of writing for-loops to iterate over all elements in a range. The new range-based for loop is much clearer than the old way using iterators. It is intended to be used when you only look at the elements in a container, you are not supposed to change the container itself since this could cause problems in the loop.

An example of how the new range-based for works, using a vector as an example:

When the vector contains an object then it’s a good idea to get a reference to the object to avoid copying the entire object in each round in the loop.

If the contents of the vector shouldn’t be changed then we can show this by getting a const reference:

We can use the auto keyword to avoid explicitly giving the type:

 

Facebookgoogle_pluslinkedinmail