C ++ functor unexpected behavior in for_each

Consider the following example:

#include <iostream> #include <vector> #include <algorithm> using namespace std; class accum { public: int sum; accum() { sum = 0; } void operator() (int a) { sum += a; printf("sum=%d\n",sum); } }; int main() { int ari[] = {2,8,5,9,1}; vector<int> vi(&ari[0], &ari[5]); accum f; for_each(vi.begin(), vi.end(), f); printf("final sum : %d\n", f.sum); } 

I expected the sum to be 25 , but prints 0 . Why does f remain unchanged? Can someone give me a detailed report on what is happening?

+4
source share
1 answer

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; // rest as before, fixing the constructor }; int sum = 0; std::for_each(vi.begin(), vi.end(), accum(sum)); printf("final sum : %d\n", 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; }); 
+5
source

All Articles