【问题标题】:How to accumulate using a Lambda function in C++?如何在 C++ 中使用 Lambda 函数进行累加?
【发布时间】:2021-04-11 05:20:09
【问题描述】:

我正在尝试使用乘法 lambda 来累积向量中的数字。

我的错误是什么?结果我得到 1,而不是 24 (= 123*4)。我的做法如下:

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

【问题讨论】:

标签: c++ c++11 lambda


【解决方案1】:

惯用的方式是:

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

你的func 做了很多奇怪的事情,我不知道你希望accumulation = a * *m.begin()++; 做什么,或者为什么你没有使用i。这会更像它:

auto func = [](int lhs, int rhs) { return lhs * rhs; };

auto accumulation = std::accumulate(m.begin(), m.end(), 1, func);

或者如果你想用floats 来做:

auto func = [](float lhs, float rhs) { return lhs * rhs; };

auto accumulation = accumulate(m.cbegin(), m.cend(), 1.f, func);

【讨论】:

    猜你喜欢
    • 2021-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多