Because s that you pass to for_each is by value. for_each takes value by value!
In C ++ 0x, you can solve this problem with for_each as,
int sum = 0; std::for_each(arr, arr+6, [&](int n){ sum += n; }); std::cout << sum ;
Output:
15
Ideon Demo: http://ideone.com/s7OOn
Or you can simply write in std::cout :
std::cout<<std::for_each(arr,arr+6,[&](int n)->int{sum += n;return sum;})(0);
Launch: http://ideone.com/7Hyla
Please note that such a different syntax is suitable for learning how std::for_each , and that it returns, but I would not recommend this syntax in real code. std::for_each
In C ++, you can write a custom transform function in a functor since
struct add { int total; add():total(0){}; void operator()(int element) { total+=element; } operator int() { return total ; } }; int main() { int arr[] = {0, 1, 2, 3, 4, 5}; int sum = std::for_each(arr, arr+6, add()); std::cout << sum; }
This is a slightly different version of Erik's second solution: http://ideone.com/vKnmA
Nawaz
source share