Use of a functor on for_each

前端 未结 4 976
陌清茗
陌清茗 2021-01-05 05:34

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

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

            


        
4条回答
  •  囚心锁ツ
    2021-01-05 06:11

    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;
    }
    

提交回复
热议问题