问题
I'm trying to accumulate the numbers in a vector using a multiplication lambda.
What is my error? I get 1 as the result, instead of 24 (= 123*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);
回答1:
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()++;
or why you leave i
unused. 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:
auto func = [](float lhs, float rhs) { return lhs * rhs; };
auto accumulation = accumulate(m.cbegin(), m.cend(), 1.f, func);
来源:https://stackoverflow.com/questions/65579216/how-to-accumulate-using-a-lambda-function-in-c