fbpx

C++: Foreach Loop

Bjarne-stroustrup
 


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.

for (container_type::iterator i = container.begin(); i != container.end(); ++i)
{
  std::cout << *i << "\n";
}

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.

void print_element(container_type::value_type const& v)
{
  std::cout << v << "\n";
}
 
std::for_each(container.begin(), container.end(), print_element);
Works with: C++11

for (auto element: container)
{
  std::cout << element << "\n";
}

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:

for (auto const& element: container)
{
  std::cout << element << "\n";
}

Of course the container elements can also be changed by using a non-const reference (provided the container isn’t itself constant):

for (auto&& element: container) //use a 'universal reference'
{
  element += 42;
}

SOURCE

Content is available under GNU Free Documentation License 1.2.