Jump to content

Loops/Foreach: Difference between revisions

m
→‎{{header|C++}}: no <iterator_concepts> in C++11
m (→‎{{header|C++}}: no <iterator_concepts> in C++11)
Line 399:
However the idiomatic way to output a container would be
<lang cpp>std::copy(container.begin(), container.end(),
std::output_iteratorostream_iterator<container_type::value_type>(std::cout, "\n"));</lang>
There's also an algorithm named <tt>for_each</tt>. However, you need a function or function object to use it, e.g.
<lang cpp>void print_element(container_type::value_type const& v)
Line 409:
std::for_each(container.begin(), container.end(), print_element);</lang>
{{works with|C++11}}
<lang cpp>#includefor <iterator_concepts>(auto element: container)
 
for (auto element: container)
{
std::cout << element << "\n";
}</lang>
Here <tt>container</tt> is the container variable, <tt>element</tt> 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:
<lang cpp>#includefor <iterator_concepts>(auto const& element: container)
 
for (auto const& element: container)
{
std::cout << element << "\n";
}</lang>
Of course the container elements can also be changed by using a non-const reference (provided the container isn't itself constant).:
<lang cpp>for (auto&& element: container) //use a 'universal reference'
{
element += 42;
}</lang>
 
=={{header|C sharp|C#}}==
Cookies help us deliver our services. By using our services, you agree to our use of cookies.