Since C++11 there are elegant way to access each element of a containers (or, more generally, sequences) – so called range-for-statement. The syntaxes are follow:
Semantically, all the above statements means “for each element in container”, where elements of container are traversed in order from container.begin()
till the container.end()
(not inclusive, please see Introduction to C++ Iterators). The expression in place of container
(in the simplest cases such as shown above, this expression is just a reference to the container) must yield an instance of a class with the defined function members begin()
and end()
, or the instance of a class for which the overloads of free functions in the enclosing scope are available to perform calls begin(container)
and end(container)
. In both cases a pair of calls container.begin()
, container.end()
or begin(container)
, end(container)
are used to obtain iterators pointed to the first element and the element one-past-the-last element of the sequence accordingly. Please note, that the auto
could be replaced with a type to which implicit conversion of the type of the elements of the sequence is allowed.
If the syntaxes (1)
and (2)
exposed above are in use, it leads each element of the container
to be copied to the controlled variable element
. While this is fine for cheap to copy values (e.g. values of built-in types, or values of types like std::string_view
), it could be costly for values of large size (e.g. values of type std::string
) which can negatively affect the performance. Thus, be careful and use syntaxes (3)
and (4)
, involving references which are more appropriate for elements that might be large. Please note, that in order to modify an element inside a range-for-statement, the controlled variable element
must be a lvalue reference, and thus, the syntax (3)
have to be used in this case.
Finally, let’s consider the example which demonstrates how to enable range-for-statement for a user-defined class: