使用std :: accumulate [英] Using std::accumulate
问题描述
我总是尽可能地尝试结合STL算法,而不是编写手动循环.但是,我很难理解 std :: accumulate
通常如何有用.每当我需要计算总和或平均值时,我几乎总是会最终求助于手动循环,因为我很难让 std :: accumulate
来完成我需要的工作.
I always try to incorporate STL algorithms wherever I can, rather than writing manual loops. However, I'm having difficulty understanding how std::accumulate
is generally useful. Whenever I need to calculate sums or averages, I almost always end up resorting to manual loops, because I have difficulty getting std::accumulate
to do what I need.
问题是我很少有一个简单的整数向量需要求和.通常,我想使用特定的成员变量求和一个对象数组.是的,我知道有一个采用BinaryFunction的 std :: accumulate
版本,但是我看到的问题是该函数需要采用两个 T
类型的值,其中, T
是 sum 的类型,而不是 operands 的类型.我在理解它的用处时遇到了麻烦.
The problem is that I rarely ever have a simple vector of integers that need to be summed. Usually, I want to sum an array of objects using a particular member variable. Yes, I know there is a version of std::accumulate
that takes a BinaryFunction, but the problem I see is that this function needs to take two values of type T
, where T
is the type of the sum, rather than the type of the operands. I'm having trouble understanding how this is useful.
考虑一个我认为很普遍的情况.我有以下课程:
Consider a case which I assume is pretty common. I have the following class:
struct Foo
{
Foo(int cost_, int id_) : cost(cost_), id(id_)
{ }
int cost;
int id;
};
现在,说我想使用 Foo :: cost
计算 Foo
对象数组的总和.
Now, say I want to calculate the sum of an array of Foo
objects, using Foo::cost
.
我想说:
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
字段求和.
The problem is, this doesn't work because std::accumulate
expects a BinaryFunction which takes in two instances of the resulting sum type - which in this case is just int
. But how is that useful to me? If my BinaryFunction takes in two int
s, I can't specify that I want to sum the cost
field.
那么,为什么 std :: accumulate
这样设计?我只是在这里看不到明显的东西吗?
So, why is std::accumulate
designed this way? Am I just not seeing something obvious here?
推荐答案
关于将两个相同类型的运算符累加,您是错误的.仅在您愿意时这样做.具体来说,使用运算符是 sum = op(sum,* iter)
.因此您的代码:
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; });
如果您不能使用lambda,那么您当然可以使用标准的活页夹或boost :: bind.
If you can't use lambda then of course you use the standard binders or boost::bind.
这篇关于使用std :: accumulate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!