在 C++ 中创建递归 for 语句

whi*_*n97 1 c++ recursion assembly for-loop statements

我想知道是否真的可以for在 C++ 中创建/定义自制语句。这里已经有人问过类似的问题:

“如何在 C++ 中创建类似 for 循环的命令?#user9282 的答案”

我所要求的是我们是否可以制作一个能够满足我们想要的性能(n 次)的for产品。for

例如,这是一个基本的 for 循环语句:

for (int i = 0; i < 10; i++) { ... }
Run Code Online (Sandbox Code Playgroud)

我想知道新的 for 循环是否会产生类似这样的结果:

int x = 20; // individual loops
int y = 3; // = amount of for-loops performed (in this case, 3)

// maybe some code generating for-loops here or something...

// result:
for (int i = 0; i < x; i++)
{
    for (int j = 0; j < x; j++)
    {
        for (int k = 0; k < x; k++)
        {
            // if "y" was equal to 5, there would be 2 more for-loops here
            instructions; // we can use "i", "j", "k", ... here
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

你认为这在 C++ 中可能吗?

[编辑:使上面的代码更清晰]

用一句话来说:我想创建一个语句(例如 if、while、for、switch),将for 循环放入for 循环(就像上面的代码将 for 循环放入 for 循环一样),这样我们就可以访问多个增量(i, j, k, ...) 在同一范围内。

Gui*_*cot 5

您可以使用包含 for 循环的递归函数轻松地做到这一点。我会这样做:

void foo() {
    for (...) {
        foo();
    }
}
Run Code Online (Sandbox Code Playgroud)

这样,您就可以根据需要执行任意数量的嵌套 for 循环。

但是,如果您想在代码中定义递归嵌套 for 循环而不定义外部函数,则可以使用 lambda:

auto recursive = [](auto func) {
    // This is needed to make a recursive lambda
    return [=](auto... args){
        func(func, args...);
    };
};

auto nestedForLoop = recursive([](auto self){
    // Here's your recursive loop!
    for (...) {
        self();
    }
});

// You can simply call `nestedForLoop` to execute loop
nestedForLoop();
Run Code Online (Sandbox Code Playgroud)