C 向量中的元素相乘

新手上路,请多包涵

我一直在寻找以下更优化的解决方案,但似乎找不到。

假设我有一个向量:

std::vector<double> vars = {1, 2, 3}

我想执行 1 * 2 * 3 我知道我可以执行以下操作:

 int multi = 1;

for(int i = 0; (i < vars.size()-1); i++)
{
    multi *= vars[i];
}

但是,有没有更多的“C++11”方式来做到这一点?我真的很想使用 lambda 来执行此操作,这样我就可以计算向量的乘法(乘积),而无需在类中使用另一个函数,我宁愿在函数中计算它。

原文由 Phorce 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1k
1 个回答

是的,像往常一样,有一个算法(虽然这个算法在 <numeric> ), std::accumulate现场示例):

 using std::begin;
using std::end;
auto multi = std::accumulate(begin(vars), end(vars), 1, std::multiplies<double>());

std::multiplies 也在 <functional> 中。默认情况下, std::accumulate 使用 std::plus ,这会将两个值相加给 operator()std::multiplies 是一个将它们相乘的仿函数。

在 C++14 中,您可以将 std::multiplies<double> 替换为 std::multiplies<> ,其 operator() 是模板化的,并且会找出类型。根据我在 Eric Niebler 的 Ranges 提案中看到的内容,它可能会在以后看起来像 vars | accumulate(1, std::multiplies<>()) ,但请谨慎对待。

原文由 chris 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题