(1) 如何创建函数的 std::vector 以便可以执行如下操作:
int main ()
{
std::vector<????> vector_of_functions;
// Add an adding function into the vector
vector_of_functions.push_back(
double function (double a, double b) {
return a + b
}
);
// Add a multiplying function into the vector
vector_of_functions.push_back(
double function (double a, double b) {
return a * b;
}
);
// Use the functions
std::cout << "5 + 7 = " << vector_of_functions[0](5, 7); // >>> 5 + 7 = 12
std::cout << "5 * 7 = " << vector_of_functions[1](5, 7); // >>> 5 * 7 = 35
return 0;
}
虽然我希望函数返回值和参数可以是任何类型,但不一定是。如果它们是固定类型,我没问题。
(2) 如何将这种 std::vector 作为函数的参数传递。
void func (std::vector<???> vof) {
std::cout << vof[0](5, 7);
};
int main ()
{
std::vector<????> vector_of_functions;
// Add an adding function into the vector
vector_of_functions.push_back(
double function (double a, double b) {
return a + b
}
);
// Add a multiplying function into the vector
vector_of_functions.push_back(
double function (double a, double b) {
return a * b;
}
);
// Call the function
func( vector_of_functions ); // >>> 12
return 0;
}
(3) 除了函数是头文件中定义的类的方法外,我如何做同样的事情。
.cpp 代码将与以前相同,除了函数将是 void ClassName::func(...);
.h 代码将是这样的:
class ClassName {
public:
ClassName();
void func(????);
}
最佳答案
如果你可以使用 C++11+,那么你可以使用 std::function和 std::bind , 或 lambda .
所以,像这样:
using func = std::function<double(double, double)>;
using vfuncs = std::vector<func>;
vfuncs vf;
vf.push_back([](double first, double second) { return first + second; });
vf.push_back([](double first, double second) { return first * second; });
/* obj is some function, which member function you want to call */
vf.push_back([&obj](double first, double second) { return obj.op(first, second); });
关于作为类方法的参数传递的函数的 c++ std::vector,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53725864/