using of std::accumulate

后端 未结 5 1345
面向向阳花
面向向阳花 2021-02-04 17:40

Need prettier solution of below example but with std::accumulate.

#include 
#include 
#include 

class Object
{
pu         


        
5条回答
  •  深忆病人
    2021-02-04 18:29

    here is an issue here, I guess the arguments are written in the wrong order should be:

    result = std::accumulate(collection.begin(), collection.end(), Object(0),Adapt())
    where Adapt is defined thus:
    
    struct Adapt { 
        static double mul(Object const &x) { return x.GetA() * x.GetB(); }
        static Object operator()(Object const &x, Object const &y) { 
           return Object(mul(x)+mul(y)) ; } };
    

    in this case of accumulate, the result is contained in a returned Object.

    If you are using gnu parallel mode the functor will give you problems if the result and the actual object referred to by the iterator are different.

    struct Adapt { 
            static double mul(Object const &x) { return x.GetA() * x.GetB(); }
            static double operator()(Object const &x, Object const &y) { 
               return mul(x)+mul(y) ; } };
    result = std::accumulate(collection.begin(), collection.end(), 0.0,Adapt())
    

    will not work with gnu parallel mode for some strange and silly reason.

提交回复
热议问题