If you’re using container classes in your C++ code (and you probably should be, even if it’s just std::array) then one of the things you’re going to want to do (a lot) is iterate through the container accessing each member in turn.
Without resorting to STL algorithms we could use a for-loop to iterate through the container.
If the above is baffling to you there are plenty of useful little tutorials on the STL on the Internet (For example, this one)
We could simplify the iterator declaration in C++11 using auto:
(See the article on auto type-deduction for details of how it works)
However, there’s a nicer syntactic sugar to improve our code: the range-for loop:
The semantics of the range-for are: For every element in the container, v, create a reference to each element in turn, item.
The above code is semantically equivalent to the following:
Not only does this save you some typing but, because it’s the compiler that’s generating the code it has a lot more potential for optimisation (for example, the compiler knows that the end() iterator is not invalidated in the body of the range-for statement, therefore it can be read once before the loop; or the compiler may choose to unroll the loop; etc.)
In case you were wondering, std::begin() and std::end() are free functions that return an iterator to the first element in the supplied container and an iterator to one-past-the-end, respectively. For most STL containers they simply call cont.begin() and cont.end(); but the functions are overloaded to handle built-in arrays and other container-like objects (see below)
Range-for loops are not limited to STL containers. They can also work with built-in arrays:
And also std::initializer_lists
Can’t wait? Download the full set of articles as a PDF, here.
To learn more about Feabhas’ Modern C++ training courses, click here.
Latest posts by Glennan Carnie (see all)
- Your handy cut-out-and-keep guide to std::forward and std::move - April 26, 2018
- Setting up Sublime Text to build your project - April 12, 2018
- “May Not Meet Developer Expectations” #77 - February 15, 2018