如何在C ++中使用Lambda函数进行累加? [英] How to accumulate using a Lambda function in C++?

查看:124
本文介绍了如何在C ++中使用Lambda函数进行累加?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用乘法lambda将向量中的数字累加.

I'm trying to accumulate the numbers in a vector using a multiplication lambda.

我的错误是什么?结果是1,而不是24(= 1 2 3 * 4).我的方法如下:

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

推荐答案

惯用的方式是:

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

您的func做很多奇怪的事情,我不知道您对accumulation = a * *m.begin()++;的期望是什么,或者为什么不使用i.会更像这样:

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

或者如果您想使用float s:

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

这篇关于如何在C ++中使用Lambda函数进行累加?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆