37

I just read the code for std::for_each:

template<class InputIterator, class Function>
Function for_each(InputIterator first, InputIterator last, Function f)
{
  for ( ; first!=last; ++first ) f(*first);
  return f;
}

and could not see any good reasons for this template function to return the input function. Does anyone have any examples on where this would be useful?

7 Answers 7

48

It's to allow you to accrue state in your function and then return it to your calling code. For instance, your function (as a functor class) could have a member int for counting the number of times it had been called.

Here is a page with some examples : https://web.archive.org/web/20171127171924/http://xenon.arcticus.com/c-morsels-std-for-each-functors-member-variables

8
  • I was told once upon a time here (by Charles Bailey, I think), that this behavior isn't guaranteed. I didn't believe him; I thought the standard, while unclear, mostly made sense in that context. (Why else would we get a function?) But just a warning, maybe this is just "standard" compiler behavior and not standard behavior.
    – GManNickG
    Jan 12, 2010 at 15:49
  • 4
    @GMan: returning the function is required by the standard (§25.1.1/2). Jan 12, 2010 at 15:57
  • 1
    Don't forget std::accumulate in <numeric>, which allows you to maintain state outside the functor in this case. Jan 12, 2010 at 17:19
  • 4
    FWIW A c++11-compliant library will return std::move(f) as per §25.2.4/3 so you can be guaranteed of being able to read the mutated state externally.
    – boycy
    Aug 22, 2012 at 15:11
  • 6
    The link is broken. May 23, 2018 at 1:33
13

It may be that Alex Stepanov had the functional programming paradigm, but you will find that both std::accumulate and std::for_each pass their operands around (the function and the accumulated value) by value, rather than by reference. Thus:

class MyFunctor
{
   Y val;
   public:
     MyFunctor() : val() {}

     void operator()( X const& x )
     {
        // do something to modify val based on x
     }

     Y getValue() const { return val; }   
};

Now if you try:

MyFunctor f;
for_each( coll.begin(), coll.end(), f );
Y y = f.getValue();

It won't work because for_each has been dealing with copies of f. Of course you could have an instance of shared_ptr<Y> internally which would therefore point to the same instance. You can also make val inside MyFunctor a reference, create it outside the loop and pass it in to MyFunctor.

However the language lets you just do:

Y y = for_each( coll.begin(), coll.end(), MyFunctor() ).getValue();

nice and convenient, all in one line.

To do the same with std::accumulate would be done like this:

class MyFunctor2
{
public:
      Y operator()( Y y, X const& x ) const
      {
         //    create a new Y based on the old one and x
        ...
      }
};

Y y = std::accumulate( coll.begin(), coll.end(), Y(), MyFunctor2() );

You could use a function (or in C++11 a lambda) instead of a functor. Note that the functor here has no state, and you pass in your initialised object as a parameter, which can be a temporary.

Now we know that Y is copyable. std::accumulate uses by value on Y, not an in-place modify. Incidentally when in-place modify really is more efficient, there is a workaround without writing a new algorithm (e.g. accumulate2 that uses += or reference modification) by using a function signature of:

Y * func( Y* py, X const & ); // function modifies *py in-place then returns py

then calling:

Y y;
std::accumulate( coll.begin(), coll.end(), &y, func );

We "know" the return value will be &y. We can make use of this if we want to access a member of Y in one place e.g.

Y y;
Z z = std::accumulate( coll.begin(), coll.end(), &y, func )->getZ();

Incidentally, a key difference to the copy in for_each and the copy in accumulate is the complexity / number of copies it will make. With for_each there will be at most 2 copies made of your functor: one as the parameter into the function and one in the return. I say "at most" because Return Value Optimisation could reduce the second of these copies. With accumulate it copies with every element in the collection, i.e O(N) rather than constant time. So if the copy is mildly expensive, the double copy in the functor will not be a major expense iterating a small number of times over large collections, whereas for accumulate it would be (and the suggestion would be the pointer hack).

2
  • Rather than pass a pointer to accumulate in, it might be nicer style to use std::reference_wrapper (and convert to the referenced type in the argument list). After all, a main use case for reference_wrapper is for functors that should not be copied, so it would make sense to apply that to state too, besides the stylistic argument in favour of not using pointers. That said - perhaps at that stage, we would be just as well to use for[_each] & capture by reference, since we are basically tricking accumulate into having different semantics, which seems like it might be defeating the point. Sep 24, 2018 at 15:16
  • 1
    Also, maybe I'm being dense, but why do you say that accumulate() will copy the functor for every element? I can't imagine why that would be necessary or practically done. The example implementation on cppreference also shows no such thing; the functor is taken by value and then called N times but never copied again. Sep 24, 2018 at 15:20
3

Returning the function basically makes std::for_each into a mediocre imitation of std::accumulate. It lets you accumulate something in the function/functor, and then retrieve that accumulated value when it's done. Almost any time you think this might be a useful thing to do, you should probably consider using std::accumulate instead.

1
  • actually std::accumulate is very clumsy.
    – CashCow
    Nov 29, 2012 at 9:01
3

If you pass in a function object, aka functor, and it has state, returning the function object allows you to access its state after iterating the sequence. Let's say you had a function object that computes three different variables from the sequence and holds them in member variables. Each time the functor is called, you update the counters. If for_each didn't return the object, how would you get the result?

Note... this is why you must always implement copy-construction, and assignment for function objects with state.

1
  • 3
    You don't HAVE TO implement the copy constructor or the assignment operator for a functor, any more than you do for any other class - the defaults will very likely do what is necessary.
    – anon
    Jan 12, 2010 at 12:57
2

its useful if you want to save (and later use) the functor state between calls for example, count the number of elements in a collections or indicate some failure to process an element by setting some internal variable.

0

Adding an example to show the usefulness (preserving the state after the iteration) of returning function object from for_each.

struct Accumulator {
    int counter = 0;
    int operator()(int i) { return counter += i; } 
};

int main()
{
    std::vector<int> vec{ 1,2,3 };

    Accumulator acc;
    std::for_each(vec.begin(), vec.end(), acc); // counter value will be lost
    cout << acc.counter;    // 0

    Accumulator sumObj = std::for_each(vec.begin(), vec.end(), acc); // counter value preserved
    cout << acc.counter;    // 0
    cout << sumObj.counter; // 6  = sum of all vector elements
}
-5

No particular reason I guess. What you can do though is using the returned function in another foreach call, thus avoiding writing the function name twice and possibly making a mistake there.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.