Use of a functor on for_each

前端 未结 4 1009
陌清茗
陌清茗 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:52

    Because the s which you pass to the for_each is by value. for_each accepts it 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
    

    Demo at ideone : http://ideone.com/s7OOn


    Or you can simple write in the std::cout itself:

    std::cout<int{sum += n;return sum;})(0);
    

    Run : http://ideone.com/7Hyla

    Note such different syntax is okay for learning purpose, as to how std::for_each works, and what it returns, but I would not recommend this syntax in real code. :-)


    In C++, you can write user-defined conversion function in the functor as,

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

    It's slightly different version from Erik second solution : http://ideone.com/vKnmA

提交回复
热议问题