As we have seen in the preceding recipe, the range-based for loops, known as for each
in other programming languages, allows you to iterate over the elements of a range, providing a simplified syntax over the standard for
loops and making the code more readable in many situations. However, range-based for loops do not work out of the box with any type representing a range, but require the presence of a begin()
and end()
function (for non-array types) either as a member or free function. In this recipe, we will see how to enable a custom type to be used in range-based for loops.
It is recommended that you read the recipe Using range-based for loops to iterate on a range before continuing with this one if you need to understand how range-based for loops work and what is the code the compiler generates for such a loop.
To show how we can enable range-based for loops for custom types representing sequences, we will use the following...