我一直在寻找一个更优化的解决方案,我似乎无法找到一个.
假设我有一个向量:
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];
}
Run Code Online (Sandbox Code Playgroud)
但是,有更多的"C++ 11"方法吗?我真的想用这个来做lambda
,所以我可以计算向量的乘法(乘积),而不需要在类中有另一个函数,我宁愿在函数内部计算它.
chr*_*ris 28
是的,像往常一样,有一个算法(虽然这个是<numeric>
),std::accumulate
(实例):
using std::begin;
using std::end;
auto multi = std::accumulate(begin(vars), end(vars), 1, std::multiplies<double>());
Run Code Online (Sandbox Code Playgroud)
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<>())
,但是带着一点点盐.
您可以使用基于范围的for循环,例如:
std::vector<double> vars = {1, 2, 3}
int multi = 1;
for (const auto& e: vars)
multi *= e;
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
10652 次 |
最近记录: |