如何遍历函数[i]()

how to iterate through function[i]()?

本文关键字:函数 遍历 何遍历      更新时间:2023-10-16

感谢您的阅读。我是编程新手,我正在尝试编写一个将遍历所有 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 方法。