是否可以使用break函数退出几个嵌套的for循环?

如果是,你会怎么做呢?你还能控制刹车出多少圈吗?


当前回答

Goto对于打破嵌套循环非常有用

for (i = 0; i < 1000; i++) {
    for (j = 0; j < 1000; j++) {
        for (k = 0; k < 1000; k++) {
             for (l = 0; l < 1000; l++){
                ....
                if (condition)
                    goto break_me_here;
                ....
            }
        }
    }
}

break_me_here:
// Statements to be executed after code breaks at if condition

其他回答

你可以使用“goto”来留下嵌套循环 下面是我的原始代码,包括“goto”

int main()
{
    string str;
    while (cin >> str)
    {
        if (str == "0")
            break;
        int sum = 0;
        for (auto ch : str)
        {
            if (ch <= 'z' && ch >= 'a')
                sum += (ch - 'a' + 1);
            else if (ch >= 'A' && ch <= 'Z')
                sum += (ch - 'A' + 1);
            else
            {
                cout << "Fail" << endl;
                goto fail;
            }
        }

        cout << sum << endl;
        fail:
    }
    return 0;
}

然而,我可以通过添加函数“计算”来避免“goto”

void calculate(const string &str)
{
    int sum = 0;
    for (auto ch : str)
    {
        if (ch <= 'z' && ch >= 'a')
            sum += (ch - 'a' + 1);
        else if (ch >= 'A' && ch <= 'Z')
            sum += (ch - 'A' + 1);
        else
        {
            cout << "Fail" << endl;
            return;
        }
    }

    cout << sum << endl;
}

int main()
{
    string str;
    while (cin >> str)
    {
        if (str == "0")
            break;
        calculate(str);
    }
    return 0;
}

打破嵌套循环的另一种方法是将两个循环分解成一个单独的函数,并在希望退出时从该函数返回。

当然,这也引发了另一个争论,即是否应该显式地从函数的任何地方返回,而不是在函数的末尾。

只是使用lambdas添加一个显式的答案:

  for (int i = 0; i < n1; ++i) {
    [&] {
      for (int j = 0; j < n2; ++j) {
        for (int k = 0; k < n3; ++k) {
          return; // yay we're breaking out of 2 loops here
        }
      }
    }();
  }

当然,这种模式有一定的局限性,显然只适用于c++ 11,但我认为它非常有用。

用一个bool变量打破任意数量的循环,如下所示:

bool check = true;

for (unsigned int i = 0; i < 50; i++)
{
    for (unsigned int j = 0; j < 50; j++)
    {
        for (unsigned int k = 0; k < 50; k++)
        {
            //Some statement
            if (condition)
            {
                check = false;
                break;
            }
        }
        if (!check)
        {
            break;
        }
    }
    if (!check)
    {
        break;
    }
}

在这段代码中,我们中断了;所有的循环。

Breaking out of a for-loop is a little strange to me, since the semantics of a for-loop typically indicate that it will execute a specified number of times. However, it's not bad in all cases; if you're searching for something in a collection and want to break after you find it, it's useful. Breaking out of nested loops, however, isn't possible in C++; it is in other languages through the use of a labeled break. You can use a label and a goto, but that might give you heartburn at night..? Seems like the best option though.