transform_reduce & 摆脱 for 循环

transform_reduce & getting rid of a for loop

所以我现在正在检查我的一些代码并尝试摆脱一些我不喜欢的 for 循环并尝试获得更多标准算法的经验.. 所以我现在的循环可以通过以下代码片段得到最好的解释:

// Defined struct
struct A {
  /* stuff */
  size_t computed_value() const { /* ... */ return value; }
};

// In other location in code
std::vector<A> vecA;
// ... insert tons of A's into vecA

size_t summed_value = 0;
for(const auto& a : vecA) {
  summed_value += a.computed_value();
}

This is the loop I want to replace with a standard algorithm, and I thought I found the perfect fit.. std::transform_reduce in numeric header, 但我的版本似乎都不是clang 或 g++ 包含此功能..? 我想到的其他一些事情是 std::accumulate 但它需要将 A 隐式转换为 int (据我所知)& std::transform 但我找不到任何方法来使用 int 或 size_t作为输出值。

注意:我现在最多只愿意使用 C++17。

有人对我应该研究的功能有任何建议吗?谢谢!

std::accumulate 函数应该可以正常工作:

size_t summed_value = std::accumulate(begin(vecA), end(vecA), 0, [](size_t acc, A const& a)
{
    return acc + a.computed_value();
});