我一直在寻找以下更优化的解决方案,但似乎找不到。
假设我有一个向量:
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 许可协议
是的,像往常一样,有一个算法(虽然这个算法在
<numeric>
),std::accumulate
( 现场示例):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<>())
,但请谨慎对待。