You're viewing a comment by wheaties and its responses.
You're viewing a comment by wheaties and its responses.
I am being sponsored by Syntress since 2007! They bought me an amazing dedicated server to run catonmat on. If you're looking web services in Chicago area, I highly recommend the Syntress guys!
I love to read science books. They make my day and I get ideas for awesome blog posts, such as Busy Beaver, On Functors, Recursive Regular Expressions and many others.
Take a look at my
Amazon wish list, if you're curious about what I have planned reading next, and want to surprise me. :)


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
fto 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 ; }Reply To This Comment