Anonymous user
Loops/Foreach: Difference between revisions
m
→{{header|C++}}: no <iterator_concepts> in C++11
(→{{header|jq}}: $a) |
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::
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>
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>
{
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#}}==
|