mardi 5 janvier 2021

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

Aucun commentaire:

Enregistrer un commentaire