Using std::accumulate

You're wrong about accumulate operator taking two of the same type. It does that only if you want to. The use the operator is specifically sum = op(sum, *iter). Thus your code:

int count = std::accumulate(stuff.begin(), stuff.end(), 0, [](int current_sum, stuff_value_t const& value) { return current_sum + value.member; });

If you can't use lambda then of course you use the standard binders or boost::bind.


use functor:

class F { // sum Foos
    F(int init = 0);
    template<class T>
    Foo operator()(const Foo &a, const T &b) const;
    operator int() const;
};

int total_cost = std::accumulate(vec.begin(), vec.end(), F(0), F());

notice you can do other things as well:

class F { // sum foo values members
    template<class T>
    T operator()(const T &a, const Foo &b) const;
};
int total_cost = std::accumulate(vec.begin(), vec.end(), int(0), F());

Tags:

C++

Stl

C++11