是否可以使用break函数退出几个嵌套的for循环?
如果是,你会怎么做呢?你还能控制刹车出多少圈吗?
是否可以使用break函数退出几个嵌套的for循环?
如果是,你会怎么做呢?你还能控制刹车出多少圈吗?
当前回答
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.
其他回答
虽然这个答案已经提出了,但我认为一个很好的方法是这样做:
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;
}
}
}
我认为goto在这种情况下是有效的:
要模拟中断/继续,你需要:
打破
for ( ; ; ) {
for ( ; ; ) {
/*Code here*/
if (condition) {
goto theEnd;
}
}
}
theEnd:
继续
for ( ; ; ) {
for ( ; ; ) {
/*Code here*/
if (condition) {
i++;
goto multiCont;
}
}
multiCont:
}
c++不支持命名循环,就像Java和其他语言一样。您可以使用goto,或创建您使用的标志值。在每个循环结束时检查标志值。如果它被设置为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;
}
}
}
}
你可以用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
如果必须同时跳出几个循环,通常会出现异常。