Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

templates

stl

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?

like image 740
larsmoa Avatar asked Jan 12 '10 12:01

larsmoa


People also ask

What does std:: for_ each return?

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.

What is std :: For_each?

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.


1 Answers

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

like image 105
Sam Holloway Avatar answered Sep 28 '22 00:09

Sam Holloway