向量中的C ++乘法元素 [英] C++ Multiplying elements in a vector
问题描述
我一直在寻找一种更理想的解决方案,但似乎找不到。
I have been looking for a more optimal solution to the following and I cannot seem to find one.
假设我有一个向量:
std :: vector< double> vars = {1,2,3}
我想执行 1 * 2 * 3
我知道我可以执行以下操作:
I want to perform 1 * 2 * 3
I know that I can do the following:
int multi = 1;
for(int i = 0; (i < vars.size()-1); i++)
{
multi *= vars[i];
}
但是,还有更多的 C ++ 11方法可以做到这一点?我真的很想使用 lambda
来做到这一点,这样我就可以计算向量的乘积(乘积),而无需在类中添加另一个函数,我宁愿将其计算出来
But, is there a more "C++11" way to do this? I really wanted to do this using lambda
and so that I can calculate the multiply (product) of the vector without having another function inside the class, I'd rather have it calculated inside the function.
推荐答案
是的,像往常一样,有一种算法(尽管该算法在中; numeric>
), std :: accumulate
(实时示例):
Yes, as usual, there is an algorithm (though this one's in <numeric>
), std::accumulate
(live example):
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
是代替它们的函子。
std::multiplies
is in <functional>
, too. By default, std::accumulate
uses std::plus
, which adds two values given to operator()
. std::multiplies
is a functor that multiplies them instead.
在C ++ 14中,您可以替换 std :: multiplies< double>
与 std :: multiplies<>
,其 operator( )
已被模板化,并将找出类型。根据我在Eric Niebler的Ranges提案中看到的内容,以后可能看起来像 vars | accumulate(1,std :: multiplies<>())
,但要加一点盐。
In C++14, you can replace std::multiplies<double>
with std::multiplies<>
, whose operator()
is templated and will figure out the type. Based on what I've seen with Eric Niebler's Ranges proposal, it could possibly later look like vars | accumulate(1, std::multiplies<>())
, but take that with a grain of salt.
这篇关于向量中的C ++乘法元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!