是否可以使用break函数退出几个嵌套的for循环?
如果是,你会怎么做呢?你还能控制刹车出多少圈吗?
是否可以使用break函数退出几个嵌套的for循环?
如果是,你会怎么做呢?你还能控制刹车出多少圈吗?
当前回答
其他语言如PHP接受break参数(即break 2;)来指定你想要跳出的嵌套循环级别的数量,但c++不接受。你必须使用一个在循环之前设置为false的布尔值,如果你想中断,在循环中设置为true,在嵌套循环之后加上一个条件中断,检查布尔值是否设置为true,如果是则中断。
其他回答
我认为goto在这种情况下是有效的:
要模拟中断/继续,你需要:
打破
for ( ; ; ) {
for ( ; ; ) {
/*Code here*/
if (condition) {
goto theEnd;
}
}
}
theEnd:
继续
for ( ; ; ) {
for ( ; ; ) {
/*Code here*/
if (condition) {
i++;
goto multiCont;
}
}
multiCont:
}
一个使用goto和标签跳出嵌套循环的代码示例:
for (;;)
for (;;)
goto theEnd;
theEnd:
我知道这是老帖子了。但我想提出一个更合理、更简单的答案。
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;
}
}
}
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.
不,别打断我的表演。这是使用后藤的最后一个据点。