我可以使用break来退出多个嵌套for循环吗?

是否有可能使用break函数来退出几个嵌套for循环? 如果是这样,你会怎么做呢? 你还可以控制中断退出多less循环?

AFAIK,C ++不支持命名循环,就像Java和其他语言一样。 你可以使用goto,或者创build一个你使用的标志值。 在每个循环结束时检查标志值。 如果它被设置为true,那么你可以跳出这个迭代。

不,不要破坏它。 这是使用goto的最后一个据点。

另一种解决嵌套循环的方法是将两个循环分解为一个单独的函数,并在退出时从该函数return

当然,这提出了另一个论点,你是否应该明确地从一个函数return ,而不是在最后。

break将只退出包含它的最里面的循环。

你可以使用goto打破任何数量的循环。

当然, goto往往被认为是有害的 。

是适当的使用restfunction[…]?

使用break和goto可以使得更难以推断程序的正确性。 在这里看到这个讨论: 迪克斯特拉并不疯狂 。

只需要使用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,但是我觉得这个模式非常有用。

虽然这个answear已经提出,我认为一个好方法是做以下几点:

 for(unsigned int z = 0; z < z_max; z++) { bool gotoMainLoop = false; for(unsigned int y = 0; y < y_max && !gotoMainLoop; y++) { for(unsigned int x = 0; x < x_max && !gotoMainLoop; x++) { //do your stuff if(condition) gotoMainLoop = 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) { j=50; k=50; } } } } 

打破几个嵌套循环的一个好方法是将你的代码重构成一个函数:

 void foo() { for(unsigned int i=0; i < 50; i++) { for(unsigned int j=0; j < 50; j++) { for(unsigned int k=0; k < 50; k++) { // If condition is true return; } } } } 

使用goto和标签来跳出嵌套循环的代码示例:

 for (;;) for (;;) goto theEnd; theEnd: 

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 

break语句终止最近的包含doforswitchwhile语句的执行。 控制传递给在已终止的语句之后的语句。

从msdn 。

我认为在这种情况下goto是有效的:

要模拟break / continue ,您需要:

打破

 for ( ; ; ) { for ( ; ; ) { /*Code here*/ if (condition) { goto theEnd; } } } theEnd: 

继续

 for ( ; ; ) { for ( ; ; ) { /*Code here*/ if (condition) { i++; goto multiCont; } } multiCont: } 

其他语言如PHP接受break(break 2;)参数来指定要跳出的嵌套循环级别的数量,但是C ++却没有。 你必须通过使用一个布尔值,在循环之前设置为false,如果你想中断,在循环中设置为true,在嵌套循环之后加上条件中断,检查布尔值是否设置为true如果是的话打破。

我知道这是旧post。 但是我会提出一些合乎逻辑和简单的答案。

 for(unsigned int i=0; i < 50; i++) { for(unsigned int j=0; j < conditionj; j++) { for(unsigned int k=0; k< conditionk ; k++) { // If condition is true j= conditionj; break; } } } 
  while (i<n) { bool shouldBreakOuter = false; for (int j=i + 1; j<n; ++j) { if (someCondition) { shouldBreakOuter = true; } } if (shouldBreakOuter == true) break; } 

你可以使用try … catch。

 try { for(int i=0; i<10; ++i) { for(int j=0; j<10; ++j) { if(i*j == 42) throw 0; // this is something like "break 2" } } } catch(int e) {} // just do nothing // just continue with other code 

如果你不得不一次突破几个循环,反正经常是个例外。

由于for循环的语义通常表示它将执行指定的次数,所以打破for循环对我来说有点奇怪。 但是,在所有情况下都不坏。 如果您正在search某个集合中的某个内容,并且在find该内容后想要分解它,那么这很有用。 但是,嵌套循环的打破在C ++中是不可能的。 它是用其他语言通过使用标记的中断。 你可以使用一个标签和一个转到,但这可能会给你晚上胃灼热..? 看起来像最好的select。