Search code examples
c++stlfunctor

Use of a functor on for_each


Why does the for_each call on functor doesn't update sum::total at the end?

struct sum
{
    sum():total(0){};
    int total;

    void operator()(int element) 
    { 
       total+=element; 
    }
};

int main()
{
    sum s;

    int arr[] = {0, 1, 2, 3, 4, 5};
    std::for_each(arr, arr+6, s);
    cout << s.total << endl; // prints total = 0;
}

Solution

  • for_each takes the functor by value - so it is copied. You can e.g. use a functor which is initialized with a pointer to an external int.

    struct sum
    {
        sum(int * t):total(t){};
        int * total;
    
        void operator()(int element)
        {
           *total+=element;
        }
    };
    
    int main()
    {
        int total = 0;
        sum s(&total);
    
        int arr[] = {0, 1, 2, 3, 4, 5};
        std::for_each(arr, arr+6, s);
        cout << total << endl; // prints total = 15;
    }
    

    Or you can use the return value from for_each

    struct sum
    {
        sum():total(0){};
        int 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);
        cout << s.total << endl; // prints total = 15;
    }