c++ - 如何将函数作为参数传递给 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
}
解决方案
好的,一些事情:
double A[n];
可变长度数组不是标准的 c++,如果你真的,真的想使用 c-array,你必须以另一种方式来做(常数大小,新的)。- 但是,你并不真正想要 c-array,你只需要一个
vector
,它会带走你所有的问题。 - 如果您的需求比您的示例更复杂,并且您确定要使用此方法,则可以传递要在您的方法中调用的函数。
这是第二点解决方案的示例,以及在第 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);
}
推荐阅读
- loops - 计算 if 循环 SPSS
- python - 检查给定范围之间的条件
- python - 切换到 Pygame 全屏模式只能工作一次
- python - Cython 包含 catkin_pkg 设置错误
- http - 如何为 Rocket.rs 设置 CORS 或 OPTIONS
- mysql - 如何优化我关于在同一个表中连接 3 个表的查询?
- resize - 在 Octave 中移动和调整子图的大小
- php - 我可以在PHP中传递一个像闭包这样的函数吗
- webrtc - 建立WebRTC连接时如何知道通过信令服务器将SDP传递给哪个设备
- c# - Azure 应用服务可以访问 github 存储库中的文件吗?