This is because std::for_each uses its functor by value, not by reference. It works internally on a copy of f , and the one you pass in remains unchanged. It returns the functor to you, so you can simply overwrite your version:
accum f = std::for_each(vi.begin(), vi.end(), accum());
Or, sticking with C ++ 03, use the accum link:
struct accum { int& sum;
Although you might just want std::accumulate :
int sum = std::accumulate(vi.begin(), vi.end(), 0);
Or, in C ++ 11, for_each with lambda:
int sum = 0; std::for_each(vi.begin(), vi.end(), [&](int a){ sum += a; });
source share