Loop through and print each element in a collection in order. Use your language’s “for each” loop if it has one, otherwise iterate through the collection in order with some other loop.
C++03 did not have a “for each” loop. The following is a generic loop which works with any standard container except for built-in arrays. The code snippet below assumes that the container type in question is typedef’d to container_type and the actual container object is named container.
However the idiomatic way to output a container would be
std::copy(container.begin(), container.end(), std::ostream_iterator<container_type::value_type>(std::cout, "\n"));
There’s also an algorithm named for_each. However, you need a function or function object to use it, e.g.
Here container is the container variable, element is the loop variable (initialized with each container element in turn), and auto means that the compiler should determine the correct type of that variable automatically. If the type is expensive to copy, a const reference can be used instead:
Of course the container elements can also be changed by using a non-const reference (provided the container isn’t itself constant):
Content is available under GNU Free Documentation License 1.2.