[英]Using std::accumulate
我总是尽可能地结合 STL 算法,而不是编写手动循环。 但是,我很难理解std::accumulate
通常是如何有用的。 每当我需要计算总和或平均值时,我几乎总是求助于手动循环,因为我很难让std::accumulate
做我需要的事情。
问题是我很少有需要求和的简单整数向量。 通常,我想使用特定的成员变量对一组对象求和。 是的,我知道有一个采用 BinaryFunction 的std::accumulate
版本,但我看到的问题是这个函数需要采用T
类型的两个值,其中T
是sum的类型,而不是操作数。 我无法理解这有什么用处。
考虑一个我认为很常见的案例。 我有以下课程:
struct Foo
{
Foo(int cost_, int id_) : cost(cost_), id(id_)
{ }
int cost;
int id;
};
现在,假设我想使用Foo::cost
计算一组Foo
对象的总和。
我想说:
std::vector<Foo> vec;
// fill vector with values
int total_cost = std::accumulate(vec.begin(), vec.end(), 0, sum_cost);
sum_cost
定义为:
int sum_cost(const Foo& f1, const Foo& f2)
{
return f1.cost + f2.cost;
}
问题是,这不起作用,因为std::accumulate
需要一个 BinaryFunction ,它接受结果总和类型的两个实例 - 在这种情况下只是int
。 但这对我有什么用? 如果我的 BinaryFunction 接受两个int
,我不能指定我想对cost
字段求和。
那么,为什么std::accumulate
是这样设计的呢? 我只是在这里没有看到明显的东西吗?
您对使用两个相同类型的累加运算符是错误的。 只有在您愿意时,它才会这样做。 运算符的使用特别是sum = op(sum, *iter)
。 因此你的代码:
int count = std::accumulate(stuff.begin(), stuff.end(), 0, [](int current_sum, stuff_value_t const& value) { return current_sum + value.member; });
如果您不能使用 lambda,那么您当然可以使用标准活页夹或 boost::bind。
使用函子:
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());
请注意,您还可以做其他事情:
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());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.