如何遍历函数[i]()
how to iterate through function[i]()?
感谢您的阅读。我是编程新手,我正在尝试编写一个将遍历所有 i 值的函数。例如,它可能是 function3(),然后迭代到随机函数 12()。这是我到目前为止所拥有的:
int main()
{
trigFunction();
system("pause");
return 0;
}
void trigFunction()
{
int i;
cout << "Welcome to Haris's Unit Circle Fun House!n";
srand(time(NULL));
i = rand()%15;
for (int x = 1; x < 15; x++)
{
functioni(); //This is obviously wrong. Is there way to do this correctly?
i = rand() % 15;
}
}
functioni() 我在文本下面定义了,例如:
void function3()
{
cout << "What is 5pi/3 in degrees?n";
cin >> answer;
if (answer == 300)
{
cout << "Correct answer!n";
}
else
{
cout << "Wrong Answer!n";
}
}
void function4()
{
cout << "What is 3pi/2 in degrees?n";
cin >> answer;
if (answer == 270)
{
cout << "Correct answer!n";
}
else
{
cout << "Wrong Answer!n";
}
}
谢谢!
编辑:有没有办法将数组实现到函数结构中?喜欢功能吗?
要记住的是,在运行时,函数名称不再真正存在。至少,不是以您可以可靠且便携地用于查找函数的形式。
您必须以某种方式将名称(或者在这种情况下,只是数字)映射到函数。执行此操作的一种简单方法是使用数组。
typedef void (*pfun)();
pfun functions[] = { function0, function1, function2, function3, function4 };
然后,您可以调用functions[i]();
请注意,数组索引从 0 开始,如果 i
获得不正确的值,情况会很糟糕。
你的方法的问题在于,跳转到任何函数(发送到处理器的低级指令)必须在编译时知道。由于迭代值可能会根据编译时未知的变量而更改,因此这不起作用。但是,有一种方法可以解决此问题 - 使用函数对象。
函数对象存储访问函数所需的跳转,但它的行为类似于可以复制的普通变量,更重要的是,存储在基于索引的数组中。这使您可以将函数对象存储在数组中,以便func_array[3]
是指向function3
的函数对象。
#include <functional>
int myfunc(int a, int b) {
return a + b;
}
int main() {
std::function<int(int, int)> func = myfunc;
int c = func(6, 9);
return 0;
}
这是一个粗略的例子,但它应该可以帮助你创建一个数组,其中函数对象指向你的所有函数。
只是要指出,这是一个使用 C++11 的示例,而 hvd 的答案是 C++03 方法。
相关文章:
- 如何在可变参数模板函数中遍历可变参数元组?
- 是否可以遍历传递给函数的数组?
- 模板类和遍历的无效构造函数
- 在使用 In Order 遍历成员函数时引发异常(堆栈溢出)时出现问题
- 编写一个通用遍历函数,允许灵活地处理具有不同参数的多个函数
- C++ 用于 BFS 遍历的 lambda 函数
- 如何调用遍历类层次结构的成员函数
- C++,一个通用递归模板函数,用于遍历树状结构
- 是否可以在 constexpr 函数中遍历枚举成员,因此值为 constexpr
- 二叉树顺序遍历错误:没有用于调用的匹配函数
- 如何遍历函数[i]()
- 遍历宏定义的函数
- 是否有一个函数用于遍历POSIX环境变量
- 从函数遍历树类
- 如何在C++中循环遍历多个函数
- 遍历二叉树的函数
- C++二进制树遍历和函数指针参数
- 使用递归函数对XML树进行预序遍历
- 通过头文件函数将遍历的数据从二进制搜索树加载到Vector中
- 我可以遍历一个在析构函数中带有头节点的链表吗?