Alex Rivera | Logout

Why does std::for_each(from, to, function) return function?

Asked 2010-01-12T12:48:46.847
38

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?

Edit
Report

2 Answers

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

answered 2010-01-12T12:54:18.613
-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.

answered 2010-01-12T12:54:23.810

Your Answer