using of std::accumulate

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

    Using c++0x:

    #include 
    #include 
    #include 
    
    class Object
    {
      public:
         Object( double a, double b ):
            a_( a ),
            b_( b )
          {}
    
        double GetA() const { return a_; }
        double GetB() const { return b_; }
        // other methods
      private:
        double a_;
        double b_;
    };
    
    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,
                                         [] (double result, const Object& obj) 
                                         {
                                           return result + obj.GetA() * obj.GetB();
                                         }
                                       ); 
    
       std::cout << "result = " << result << std::endl;
    
       return 0;
    } 
    

提交回复
热议问题