【问题标题】:transform_reduce & getting rid of a for looptransform_reduce & 摆脱 for 循环
【发布时间】:2020-01-15 11:43:08
【问题描述】:

所以我现在正在查看我的一些代码并尝试摆脱一些我不喜欢的 for 循环并尝试获得更多使用标准算法的经验.. 因此,我现在拥有的循环可以通过以下代码 sn-p 得到最好的解释:

// 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();
}

这是我想用标准算法替换的循环,我想我已经找到了完美的匹配.. numeric 标头中的std::transform_reduce,但似乎我的 clang 或 g++ 版本都没有这个功能包括..? 我想到的其他一些事情是std::accumulate,但它需要将 A 隐式转换为 int(据我所知)和std::transform,但我找不到任何使用 int 或 size_t 作为输出值的方法.

注意:目前我只愿意使用 C++17。

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

【问题讨论】:

  • 向上和包括 C++17?

标签: c++ c++-standard-library


【解决方案1】:

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

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

【讨论】:

  • 谢谢!我应该进一步阅读累积文档..
猜你喜欢
  • 2020-08-04
  • 1970-01-01
  • 2014-02-12
  • 1970-01-01
  • 1970-01-01
  • 2017-06-23
  • 1970-01-01
  • 1970-01-01
  • 2017-04-13
相关资源
最近更新 更多