Use of a functor on for_each

前端 未结 4 978
陌清茗
陌清茗 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 05:54

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

提交回复
热议问题