using of std::accumulate

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

    Update 2: Boost.Lambda makes this a piece of cake:

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

    Update: This has been bugging me for a while. I can't just get any of the STL algorithms to work in a decent manner. So, I rolled my own:

    // 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 
    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 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(), 
                            mem_fun_ref(&strange::value)) << endl;
    }
    

    Of course, the original solution still holds: The easiest is to implement an operator+. In this case:

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

    and make it a friend of Object or member (look up why you may prefer one over the other):

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

    and you're done with:

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

    My earlier approach doesn't work because we need a binary_function.

    std::accumulate manual.

提交回复
热议问题