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?
13.8 The for_each() Algorithm The argument function is guaranteed to be invoked only once for each element in the sequence. The std::for_each() algorithm itself returns the value of the third argument, although this is usually ignored.
std::for_each is an STL algorithm that takes a collection of elements (in the form of a begin and end iterator) and a function (or function object), and applies the function on each element of the collection. It has been there since C++98.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With