using of std::accumulate

后端 未结 5 1418
面向向阳花
面向向阳花 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:25

    do changes in Calculator and main function.

    struct Calculator
    {
        double operator() ( double result, const Object& obj )
        {
            return result + ( obj.GetA() * obj.GetB());
        }
    
    };
    
    int main()
    {
        std::vector< Object > collection;
        collection.push_back( Object( 1, 2 ) );
        collection.push_back( Object( 3, 4 ) );
    
        double result = std::accumulate( collection.begin(), collection.end(), 0, Calculator() );
        std::cout << "result = " << result << std::endl;
    
        return 0;
    }
    

    also it could be better:

    double sumABProduct( double result, const Object& obj )
    {
        return result + ( obj.GetA() * obj.GetB());
    }
    
    double result = std::accumulate( collection.begin(), collection.end(), 0, sumABProduct );
    

提交回复
热议问题