Range-based For Loops in C++11 – Basics and its usage on STL containers

Trying to understand the power of range-based for loops in C++11.
Range-based for loops is arguably one of the most powerful features of C++11. It introduces a shorter syntax for iterating through the elements of a container (C-arrays, std::vector, std::list, std::map, etc.). This feature was already included for many years in other similar-to-C++ static typed languages, such as, Java and C#, etc. and now it has found its place in C++…. which is great, because C++ programmers were tired of using the (very) old syntax for iterating through the elements of a container.
In this post, I’m going to show you its usage and how it makes the syntax easier to read and makes your code look modern.

Range-based For Loops in C++11 – Basics and its usage on STL containers

Below is its usage on STL containers:

You can compile it with g++ and run the program as follows (assuming the file is saved as main.cpp):

Running the program prints following to the console:

It executes a loop over a range. Here, we are inferring the type of elements in our “number” container (int in this case) using “auto“. Its equivalent in the previous versions of C++ (i.e., C++03) would look like the following:

Or using iterators, it would look like the following:

It can be used to iterate through the elements in C-arrays as well.

The same syntax can be used for similar-to-vector containers like std::list, std::deque, etc.

Changing the values in a container

You can use the reference to change the values in a container:

Using range-based for loop with std::map

You can use range-based for loops with std::map as well.

It is a good practice to make the parameter in the loop a reference for efficiency. You could also consider making it const if you want a read-only view of the values.