使用std :: accumulate

时间:2009-03-06 11:11:59

标签: c++ stl

需要更优秀的以下示例解决方案,但需要使用std :: accumulate。

#include <algorithm>
#include <vector>
#include <iostream>

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

class Calculator
{
public:
    Calculator( double& result ):
        result_( result )
    {}

    void operator() ( const Object& object )
    {
        // some formula
        result_ += object.GetA() * object.GetB();
    }
private:
    double& result_;
};

int main()
{
    std::vector< Object > collection;
    collection.push_back( Object( 1, 2 ) );
    collection.push_back( Object( 3, 4 ) );

    double result = 0.0;
    std::for_each( collection.begin(), collection.end(),
                   Calculator( result ) );

    std::cout << "result = " << result << std::endl;

    return 0;
}

5 个答案:

答案 0 :(得分:11)

对计算器和主要功能进行更改。

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

也可能更好:

double sumABProduct( double result, const Object& obj )
{
    return result + ( obj.GetA() * obj.GetB());
}

double result = std::accumulate( collection.begin(), collection.end(), 0, sumABProduct );

答案 1 :(得分:3)

更新2: Boost.Lambda让这件事变得轻而易举:

// headers
#include <boost/lambda/lambda.hpp>
#include <boost/lambda/bind.hpp>
using namespace boost::lambda;
// ...
cout << accumulate(dv.begin(), dv.end(), 
                   0, 
                   _1 += bind(&strange::value, _2)) //strange defined below
     << endl;

更新:这一直困扰着我。我不能让任何STL算法以合适的方式工作。所以,我自己动手:

// include whatever ...
using namespace std;

// custom accumulator that computes a result of the 
// form: result += object.method();
// all other members same as that of std::accumulate
template <class I, class V, class Fn1, class Fn2>
V accumulate2(I first, I last, V val, Fn1 op, Fn2 memfn) {
    for (; first != last; ++first)
        val = op(val, memfn(*first));
    return val;
}

struct strange {
    strange(int a, int b) : _a(a), _b(b) {}
    int value() { return _a + 10 * _b; }
    int _a, _b;
};

int main() {
    std::vector<strange> dv;
    dv.push_back(strange(1, 3));
    dv.push_back(strange(4, 6));
    dv.push_back(strange(20, -11));        
    cout << accumulate2(dv.begin(), dv.end(), 
                        0, std::plus<int>(), 
                        mem_fun_ref(&strange::value)) << endl;
}

当然,原始解决方案仍然有效: 最简单的方法是实现operator+。在这种情况下:

double operator+(double v, Object const& x) {
        return v + x.a_;
}

并使其成为Object或成员的朋友(查找为什么您可能更喜欢其中一个):

class Object
{
   //...
  friend double operator+(double v, Object const& x);

你完成了:

 result = accumulate(collection.begin(), collection.end(), 0.0);

我之前的方法不起作用,因为我们需要binary_function

std::accumulate手册。

答案 2 :(得分:1)

这里有一个问题,我猜参数写错的顺序应该是:

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

在这种accumulate的情况下,结果包含在返回的Object中。

如果使用gnu并行模式,如果迭代器引用的结果和实际对象不同,仿函数会给你带来问题。

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())
由于一些奇怪而愚蠢的原因,

无法使用gnu并行模式。

答案 3 :(得分:1)

使用c ++ 0x:

#include <numeric>
#include <vector>
#include <iostream>

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

答案 4 :(得分:0)

人们希望这是作业......

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(), Object(0,0),Adapt() );

假设您不允许触摸Object的声明。