我正在尝试使用乘法 lambda 来累积向量中的数字。
我的错误是什么?我得到 1 作为结果,而不是 24 (= 123*4)。我的做法如下:
std::function<float(float a, int x)> func;
std::vector<int> m{ 1, 2, 3, 4 }; // <-- Multiply: 1*2*3*4 = 24
float accumulation = 1.0f;
func = [&accumulation, &m](float a, int i) {
accumulation = a * *m.begin()++;
return accumulation;
};
accumulation = accumulate(m.cbegin(), m.cend(), accumulation, func);
惯用的方法是:
auto accumulation = std::accumulate(m.begin(), m.end(), 1, std::multiplies{});
Your func
做了很多奇怪的事情,我不知道你希望做什么accumulation = a * *m.begin()++;
或者你为什么离开i
没用过。这更像是这样:
auto func = [](int lhs, int rhs) { return lhs * rhs; };
auto accumulation = std::accumulate(m.begin(), m.end(), 1, func);
或者如果你想这样做float
s:
auto func = [](float lhs, float rhs) { return lhs * rhs; };
auto accumulation = accumulate(m.cbegin(), m.cend(), 1.f, func);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)