简体   繁体   English

如何在 C++ 中使用 Lambda function 进行累积?

[英]How to accumulate using a Lambda function in C++?

I'm trying to accumulate the numbers in a vector using a multiplication lambda.我正在尝试使用乘法 lambda 来累积向量中的数字。

What is my error?我的错误是什么? I get 1 as the result, instead of 24 (= 1 2 3*4).结果我得到 1,而不是 24 (= 1 2 3*4)。 My approach is as follows:我的方法如下:

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);

The idiomatic way would be:惯用的方法是:

auto accumulation = std::accumulate(m.begin(), m.end(), 1, std::multiplies{});

Your func does a lot of odd stuff and I have no idea what you hope for with accumulation = a * *m.begin()++;你的func做了很多奇怪的事情,我不知道你希望用accumulation = a * *m.begin()++; or why you leave i unused.或者你为什么不使用i This would be more like it:这更像是:

auto func = [](int lhs, int rhs) { return lhs * rhs; };

auto accumulation = std::accumulate(m.begin(), m.end(), 1, func);

Or if you want to do it with float s:或者,如果您想使用float s:

auto func = [](float lhs, float rhs) { return lhs * rhs; };

auto accumulation = accumulate(m.cbegin(), m.cend(), 1.f, func);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM