首页 > 解决方案 > 如何将函数作为参数传递给 C++ 中的函数

问题描述

我有方法(根据一些数据点void DE(...)查找函数的参数y=f(x, a, b...)。当我想使用具有其他数量参数的函数时,我需要注释第一个函数,编写第二个函数,(X.PAR[i][1],..., X.PAR[i][n])每次使用时添加这个函数的参数func(y, x, param_1....param_n)。我怎样才能使函数成为函数f(double x1, x2,...xn)的参数DE,所以我不需要为每个其他函数更改我的程序?

double f(double x1, x2,...xn){

}
void DE(int n){
 double A[n];
 fill(A) //some function that makes up values
 cout<<f(A[0], A[1],...A[n-1]);//if I change number of arguments in f, I also need to change it here
}

标签: c++functionarguments

解决方案


好的,一些事情:

  1. double A[n];可变长度数组不是标准的 c++,如果你真的,真的想使用 c-array,你必须以另一种方式来做(常数大小,新的)。
  2. 但是,你并不真正想要 c-array,你只需要一个vector,它会带走你所有的问题。
  3. 如果您的需求比您的示例更复杂,并且您确定要使用此方法,则可以传递要在您的方法中调用的函数。

这是第二点解决方案的示例,以及在第 3 点接近解决方案的提示:

#include <iostream>
#include <vector>
using namespace std;

void fill(vector<double> &vec)
{
    vec.push_back(12);
    vec.push_back(1.3);
    vec.push_back(4.7);
}

double f(const vector<double> &vec)
{
    double some_value = 1;
    for(double val:vec)
        some_value = some_value*val;
    return some_value;
}

double fn(double a1, double a2, double an)
{
    double some_value = 1;
    some_value = some_value*a1*a2*an;
    return some_value;
}
void DE()
{
   vector<double> A;
   fill(A); //some function that makes up values
   cout<<f(A)<<endl;
}
template<typename Func>
void DE2(Func func)
{
   double A[3];
   A[0] = 12;
   A[1] = 1.5;
   A[2] = 4.6;
   cout<<func(A[0], A[1], A[2])<<endl;
}

int main()
{
    DE();
    DE2(fn);
}

推荐阅读