Why does the for_each
call on functor doesn\'t update sum::total
at the end?
struct sum
{
sum():total(0){};
int total;
This happens due to std::for_each requires the functor to be passed by value . A workaround for your solution:
struct sum
{
sum():total(0){};
int total;
sum(sum & temp)
{
total = temp.total;
}
void operator()(int element)
{
total+=element;
}
};
int main()
{
sum s;
int arr[] = {0, 1, 2, 3, 4, 5};
s = std::for_each(arr, arr+6, s); // result of for_each assigned back to s
cout << s.total << endl; // prints total = 0;
}