gpt4 book ai didi

c++ - 使用 std::accumulate

转载 作者:IT老高 更新时间:2023-10-28 22:35:49 27 4
gpt4 key购买 nike

我总是尽可能地尝试结合 STL 算法,而不是编写手动循环。但是,我很难理解 std::accumulate 通常是如何有用的。每当我需要计算总和或平均值时,我几乎总是求助于手动循环,因为我很难让 std::accumulate 来做我需要的事情。

问题是我很少有需要求和的简单整数 vector 。通常,我想使用特定的成员变量对对象数组求和。是的,我知道有一个版本的 std::accumulate 采用 BinaryFunction,但我看到的问题是该函数需要采用两个 T 类型的值,其中Tsum 的类型,而不是操作数 的类型。我无法理解这有什么用处。

考虑一个我认为很常见的案例。我有以下类(class):

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,它接受 resulting sum 类型的两个实例 - 在这种情况下是只是 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,那么您当然可以使用标准绑定(bind)器或 boost::bind。

关于c++ - 使用 std::accumulate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5158578/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com