如何在c++中跳出嵌套循环

How do you break out of nested loops in C++?

本文关键字:嵌套循环 c++      更新时间:2023-10-16

我是c++的初学者,我想知道如何跳出嵌套循环。是否有break(2)

#include <iostream>
using namespace std;
int main() {
    for (int x = 5; x < 10; x++) {
        for (int j = 6; j < 9; j++) {
            for (int b = 7; b < 12; b++) {
                // Some statements
                // Is break(2) right or wrong
                // or can I use 'break; break;'?
            }
        }
    }
}

您可以使用goto。本质上是相同的函数

#include <iostream>
using namespace std;
int main() {
    for(int x = 5; x < 10; x++) {
        for(int j = 6; j < 9; j++) {
            for(int b = 7; b < 12; b++) {
                if (condition)
                    goto endOfLoop;
            }
        }
    }
    endOfLoop:
    // Do stuff here
}

不,不幸的是没有break(2)(或者可能是幸运的,取决于你对作用域深度嵌套的看法)。

有两种主要方法来解决这个问题:

  1. break之前设置一个标志,告诉外部循环停止。
  2. 将一些嵌套循环放入函数中,以便它们可以执行break,也可以执行return跳出。例如:

// returns true if should be called again, false if not
bool foo() {
    for(int j = 6; j < 9; j++) {
        for(int b = 7; b < 12; b++) {
            if (something) {
                break; // one level
            }
            if (whatever) {
                return true; // two levels
            }
            if (another) {
                return false; // three levels
            }
        }
    }
}
int main() {
    for(int x = 5; x < 10; x++) {
        if (!foo()) {
            break;
        }
    }
}