Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Not counting BOOST_FOREACH which AraK already suggested, you have the following two options in C++ today:</p> <pre><code>void function(Foo&amp; arg){ blah(arg.x, arg.y); woop(arg.z); } std::for_each(someVariable.begin(), someVariable.end(), function); struct functor { void operator()(Foo&amp; arg){ blah(arg.x, arg.y); woop(arg.z); } }; std::for_each(someVariable.begin(), someVariable.end(), functor()); </code></pre> <p>Both require you to specify the "body" of the loop elsewhere, either as a function or as a functor (a class which overloads <code>operator()</code>). That <em>might</em> be a good thing (if you need to do the same thing in multiple loops, you only have to define the function once), but it can be a bit tedious too. The function version may be a bit less efficient, because the compiler is generally unable to inline the function call. (A function pointer is passed as the third argument, and the compiler has to do some more detailed analysis to determine which function it points to)</p> <p>The functor version is basically zero overhead. Because an object of type <code>functor</code> is passed to <code>for_each</code>, the compiler knows exactly which function to call: <code>functor::operator()</code>, and so it can be trivially inlined and will be just as efficient as your original loop.</p> <p>C++0x will introduce lambda expressions which make a third form possible.</p> <pre><code>std::for_each(someVariable.begin(), someVariable.end(), [](Foo&amp; arg){ blah(arg.x, arg.y); woop(arg.z); }); </code></pre> <p>Finally, it will also introduce a range-based for loop:</p> <pre><code>for(Foo&amp; arg : my_someVariable) { blah(arg.x, arg.y); woop(arg.z); } </code></pre> <p>So if you've got access to a compiler which supports subsets of C++0x, you might be able to use one or both of the last forms. Otherwise, the idiomatic solution (without using Boost) is to use <code>for_each</code>like in one of the two first examples.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload