You should put down accumulate instead of for_each in your C++ example as for_each is not required to pass the previous functor's state to the next call. That is, you could wind up with even == 0 and odd == 1 instead of 25 and 30.
How would it lose the state? The doc clearly states that for_each(first, last, f) applies f to the result of dereferencing every iterator in the range [first, last).
The standard just requires a copy of f to be returned. This means that, for instance, the following implementation is perfectly legal:
template< typename InputIterator, typename Function >
Function
for_each( InputIterator first, InputIterator last, Function f )
{
if ( first != last ) {
f( *first ) ;
for_each( first + 1, last, f ) ;
}
return f ;
}
This is a typical gotcha for C++ beginners.
(There are also other small oversights in the code, but this is the main one.)
PS: Also, I think that standard-wise the only occurrence of the term "functor" I've seen is in the draft specification for unique_ptr (but I'd have to check if it's still there; if so it ought probably be replaced by "function object"). But of course it's a term in common usage, sometimes referring to classes, sometimes to objects (instances).
Oops, I forgot to stick to input iterators, sorry. It should of course be:
template< typename InputIterator, typename Function >
Function
for_each( InputIterator first, InputIterator last, Function f )
{
if ( first != last ) {
f( *first ) ;
++ first ;
for_each( first, last, f ) ;
}
return f ;
}
You should put down accumulate instead of for_each in your C++ example as for_each is not required to pass the previous functor's state to the next call. That is, you could wind up with even == 0 and odd == 1 instead of 25 and 30.
Comment Responses
How would it lose the state? The doc clearly states that for_each(first, last, f) applies f to the result of dereferencing every iterator in the range [first, last).
The standard just requires a copy of
f
to be returned. This means that, for instance, the following implementation is perfectly legal:This is a typical gotcha for C++ beginners.
(There are also other small oversights in the code, but this is the main one.)
PS: Also, I think that standard-wise the only occurrence of the term "functor" I've seen is in the draft specification for unique_ptr (but I'd have to check if it's still there; if so it ought probably be replaced by "function object"). But of course it's a term in common usage, sometimes referring to classes, sometimes to objects (instances).
Oops, I forgot to stick to input iterators, sorry. It should of course be:
Reply To This Comment