Why can't for_each modify its functor argument?

后端 未结 3 1831
猫巷女王i
猫巷女王i 2020-12-31 18:00

http://www.cplusplus.com/reference/algorithm/for_each/
Unary function taking an element in the range as argument. This can either be a pointer to a

相关标签:
3条回答
  • 2020-12-31 18:16

    The function object is taken by value. for_each returns the function object, so if you change it to:

    multiply = std::for_each(vec.begin(),vec.end(),multiply);
    

    you get the expected output.

    0 讨论(0)
  • 2020-12-31 18:26

    The semantics of For_each dont fit into what you are trying to do. accumulate does exactly what you are trying, use that instead.

    0 讨论(0)
  • 2020-12-31 18:32

    While James is correct, using std::accumulate with std::multiplies would be more correct, probably:

    #include <iostream>
    #include <functional>
    #include <numeric>
    #include <vector>
    
    int main(void)
    {
        std::vector<double> vec;
        vec.push_back(1);
        vec.push_back(2);
        vec.push_back(3);
    
        double result = std::accumulate(vec.begin(), vec.end(),
                                        1.0, std::multiplies<double>());
    
        std::cout << "\nResult: " << result << std::endl;
    
    }
    

    With your for_each version, you don't really need to copy the functor again, rather:

    double result = std::for_each(vec.begin(), vec.end(), multiply).result();
    

    Or C++0x, for fun:

    double result = 1;
    std::for_each(vec.begin(), vec.end(), [&](double pX){ result *= pX; });
    
    0 讨论(0)
提交回复
热议问题