gpt4 book ai didi

C++:从捕获函数参数的函数返回lambda表达式

转载 作者:行者123 更新时间:2023-11-30 03:29:32 25 4
gpt4 key购买 nike

以下函数应该采用多项式的系数并从中创建时间函数:

std::function<double(double)> to_equation(const std::vector<double>& coefficients)
{
return [coefficients](double t)
{
auto total = 0.0;
for (int i = 0; i < coefficients.size(); i++)
{
total += coefficients[i] * pow(t,i);
return total;
}
};
}

它应该可以按如下方式使用:

std::vector<double> coefficients = {1.0,2.0,3.0};
auto f = to_equation(coefficients);
auto value = f(t);

但是代码没有按预期工作,因为在执行 f(t) 时,没有使用传递给 to_equation(coefficients) 的系数,但是从上下文中神奇地捕获了一些完全不同的值。发生了什么事,我该如何解决?

最佳答案

那么,您将返回一个按值捕获系数 的 lambda。如果您将一些 vector 传递给 to_equation 函数,所有值都将被复制,并且 lambda 将不再引用原始 vector 。

我建议这个解决方案:

// auto is faster than std::function
auto to_equation(const std::vector<double>& coefficients)
{
// Here, you capture by reference.
// The lambda will use the vector passed in coefficients
return [&coefficients](double t)
{
// ...
};
}

但是,有时您必须处理这样的代码:

std::function<double(double)> f;

{
std::vector<double> coeff{0.2, 0.4, 9.8};

f = to_equation(coeff);
}

auto result = f(3);

这很糟糕, vector coeff 的生命周期不够长,我们在 vector 被销毁后引用它。

我建议将此重载添加到您的函数中:

// when a vector is moved into coefficients, move it to the lambda
auto to_equation(std::vector<double>&& coefficients)
{
// Here, you capture by value.
// The lambda will use it's own copy.
return [coeff = std::move(coefficients)](double t)
{
// ...
};
}

然后,可以通过两种方式调用您的函数:

std::vector<double> coeff{0.2, 0.4, 9.8};

auto f1 = to_equation(coeff); // uses reference to coeff
auto f2 = to_equation({0.2, 0.4, 9.8}) // uses value moved into the lambda

关于C++:从捕获函数参数的函数返回lambda表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45652352/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com