Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
482 views
in Technique[技术] by (71.8m points)

c++11 - How to accumulate using a Lambda function in C++?

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...