繁体   English   中英

在C ++中用作输入

[英]Functions as Inputs in C++

我正在用C ++编写牛顿方法的函数。
我希望能够指定要在算法中使用的函数,但我希望将其作为输入。

例如:

double newton(f,df,tolerance,initial_guess,max_iterations)

其中fdf分别是函数及其导数

但是我该怎么做呢?

您可以使用模板执行此操作:

#include <math.h>
#include <stdio.h>

template<class F>
void foo(F f, double x) {
  printf("f(0) = %f\n", f(x));
}

int main() {
  foo(sinf, 0);
  foo(cosf, 0);
}

输出:

f(0) = 0.000000
f(0) = 1.000000

您将声明一个函数指针作为输入:这是一个基本示例:

void printNumber (int input) {
    cout << "number entered: " << input << endl;
}

void test (void (*func)(int), int input) {
    func(input);
}

int main (void) {
    test (printNumber, 5);
    return 0;
}

测试中的第一个参数说:接受一个名为func的函数,该函数具有一个int作为输入,并返回void。 您将对函数及其派生函数执行相同的操作。

作为一种替代方法,您可以在C ++ 11中这样编写。

(根据@Anycom的代码^ _ ^修改)

#include <math.h>
#include <stdio.h>
#include <functional>


void foo(std::function<double(double)> fun, double x) {
  printf("f(0) = %f\n", fun(x));
}

int main() {
  foo(sinf, 0);
  foo(cosf, 0);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM