This is the functor code that I copied from http://www.catonmat.net/blog/on-functors/.
#include <algorithm>
#include <iostream>
#include <list>
class EvenOddFunctor {
int even_;
int odd_;
public:
EvenOddFunctor() : even_(0), odd_(0) {}
void operator()(int x) {
if (x%2 == 0) even_ += x;
else odd_ += x;
}
int even_sum() const { return even_; }
int odd_sum() const { return odd_; }
};
int main() {
EvenOddFunctor evenodd;
int my_list[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
// ??? why assign
evenodd = std::for_each(my_list,
my_list+sizeof(my_list)/sizeof(my_list[0]),
evenodd); // ???
std::cout << "Sum of evens: " << evenodd.even_sum() << "\n";
std::cout << "Sum of odds: " << evenodd.odd_sum() << std::endl;
// output:
// Sum of evens: 30
// Sum of odds: 25
}
Why do we need assigning the value back to evanodd
object after the operation as in evenodd = std::for_each(my_list,
? I thought that as the evenodd object is updated from the std::for_each, I don't need the assignment operation, but without this assignment, the results show 0.
std::for_each
accepts the functor by value, that means it modifies a local copy. The assignment gets that local copy back so you can actually see the modified version.
This is important as your functor has mutable state that you are interested in, in particular evenodd.even_sum
and evenodd.odd_sum
.