How to accumulate using a Lambda function in C++?

放肆的年华 提交于 2021-02-05 12:17:25

问题


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 floats:

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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!