从 C++11 中的列表中选择并计算函数
Choose and evaluate a function from a list in C++11
使用C++,我需要从列表中选择一个函数,然后使用一些输入评估该函数。我知道足够危险,我已经通过一些魔法解决了我的问题,但我对我的解决方案有疑问。这是一个最小的工作示例:
double foo(double x) {return x+2;}
double bar(double x) {return x*7;}
double baz(double x) {return x-1;}
int main() {
double x = 3;
auto func_list = {foo,bar,baz};
// This is chosen from an external source,
// setting to a fixed value for the example
int random_choice = 1;
double y = (*(func_list.begin()+random_choice))(x);
return 0;
}
问题:这是从列表中选择函数并对其进行评估的正确方法吗? auto
这是一把双刃剑,它创造了一些东西,但我不知道它是什么类型。
[auto] 创造了一些东西,但我不知道它是什么类型。
将支撑列表(相同类型)分配给auto
时,例如:
auto func_list = {foo,bar,baz};
该列表将始终转换为std::initializer_list
。 这就是自动变量的类型。
这是正确的方法吗?
从那里,您的剩余代码是有效的。 是否是正确的方法将始终取决于您。
首先,
auto func_list = {foo,bar,baz};
创建类型为 std::initializer_list<double (*)(double)>
的变量。虽然您拥有的功能有效,但最好使用更预期的容器:
std::vector<double(*)(double)> func_list = {foo, bar, baz};
无论哪种方式,您都可以编写一个random_select
函数,例如:
template <typenme Iter>
auto random_select(Iter begin, Iter end) -> decltype(*begin)
{
static std::random_device rd;
static std::mt19937 gen(rd());
std::uniform_int_distribution<> dis(0, std::distance(begin, end) - 1);
return *std::next(begin, dis(gen));
}
template <typename C>
auto random_select(const C& cont) -> decltype(*cont.begin()) {
return random_select(cont.begin(), cont.end());
}
double y = random_select(func_list)(x);
你说,
auto
这是一把双刃剑,它创造了一些东西,但我不知道它是什么类型。
您可以创建一个函数指针数组并使用该数组,如果这样可以简化操作。喜欢:
double foo(double x) {return x+2;}
double bar(double x) {return x*7;}
double baz(double x) {return x-1;}
int main() {
double x = 3;
// Use the compiler to get a type that can be used to define an array.
typedef decltype((&foo)) function_type;
// Define an array of function pointers.
function_type func_list[] = {foo, bar, baz};
// Now use the array to call one of the functions.
int random_choice = 1;
double y = func_list[random_choice](x);
return 0;
}
如果你不想使用编译器魔术,你可以使用:
int main() {
double x = 3;
// Define a function type using typedef
typedef double (*function_type)(double);
// Define an array of function pointers.
function_type func_list[] = {foo, bar, baz};
// Now use the array to call one of the functions.
int random_choice = 1;
double y = func_list[random_choice](x);
return 0;
}
相关文章:
- 为什么"do while"循环不断退出,即使条件计算结果为 false?
- 递归函数计算序列中的平方和(并输出过程)
- 如何使用默认参数等选择模板专业化
- (C++)分析树以计算返回错误值的简单算术表达式
- 如何(从固定列表中)选择一个数字序列,该序列将与目标数字相加
- 我的字符计数代码计算错误.为什么
- 在计算中使用二的幂有多有利可图
- 选择要调用的构造函数
- C++选择排序算法中的逻辑错误
- 如何计算文件中的"columns"数?
- QTreeView幻灯片多选后无法使用单击选择
- 计算排序向量的向量中唯一值的计数
- 如何使用 std::累积在 C++ 中计算总和立方体
- 从两列中选择一个数字并进行计算
- 如何在选择排序中计算比较?
- 计算选择排序中的比较次数时出错
- 用于选择计算机组的数据结构
- 从 C++11 中的列表中选择并计算函数
- c++获取用户选择的日期与实际日期之间的年份(计算日、月、年)
- 在映射或unordered_map之间选择由计算的双精度值组成的键