gpt4 book ai didi

c++ - 减少参数数量

转载 作者:太空宇宙 更新时间:2023-11-04 16:07:45 25 4
gpt4 key购买 nike

假设我有一个方法:

std::vector<double> minimize(double (*f)(const std::vector<double>& x))

采用函数 f(x) 并找到使它最小化的 x。假设我想最小化一个函数 g(x, a)(关于 x),它也接受参数 a 作为参数:

double g(const std::vector<double>& x, const double a)

如果 a 的值仅在运行时已知,我如何(在 c++11 中)使用方法 minimize 做到这一点?

最佳答案

您可以轻松使用 lambda。

minimize([=](const std::vector<double>& x) { return g(x, a); });

这是假设您将函数更改为使用 std::function 而不是函数指针。函数指针非常有限,根本不能做任何有趣的事情,就像这样,所以最好忘记它们的存在。

关于c++ - 减少参数数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32682228/

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