C++中函数的线性组合

问题描述 投票:0回答:1

假设我们有以下内容:

// some functions
double f1( double x );
double f2( double x );
double f3( double x );
// coefficients
double c1, c2, c3;
// input variable
double x;

我们需要计算

我们可以使用直接方法

double y = c1*f1(x) + c2*f2(x) + c3*f3(x);  // x is passed 3 times as an argument

但这不是我想要实现的目标。我需要以函子术语执行此操作,即使用高阶函数。在伪代码中它一定是这样的:

auto F = c1*f1 + c2*f2 + c3*f3; // resulting functor
double y = F(x);                // one and only passing the x value instead of 3 times

有没有办法可以使用标准 C++ 库或 Boost(例如 Boost.HOF)来实现此目的?或者你能建议我另一个实现这个功能的图书馆吗?代码不必完全像这样。主要的事情是定义算术运算并将其应用于函数而不是数字,并且仅传递 x 值一次。

c++ boost functor higher-order-functions
1个回答
0
投票

通常,您可以在 C++ 中对高阶函数使用 lambda 表达式,尽管它们并不是绝对必要的:

double c1 = 1, c2 = 2, c3 = 3;
auto F = [c1, c2, c3](double x) {
    return c1 * f1(x) + c2 * f2(x) + c3 * f3(x);
};
double result = F(5);

请参阅 什么是 lambda 表达式,何时应该使用它?

© www.soinside.com 2019 - 2024. All rights reserved.