在C ++中打破嵌套循环 [英] Breaking out of nested loops in C++

查看:150
本文介绍了在C ++中打破嵌套循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有下面的代码,当break的时候,我们想打破内外循环而不是内循环,直接去blablabla。我们如何在C ++中做到这一点?



$ p $ for(int i = 0; i< m; i ++){$ b $ (b)for(int j = 0; j if(some condition){
//做某事并打破...
break; //从内部循环中跳出






$ $ $










$ b $


解决方案

直接转到[...]听起来像是一个完美的作业转到。 (int i = 0; i for(int) j = 0; j if(some condition){
//做一些事情并打破...
goto afterLoop; //打破两个循环
}
}
}
after循环:
//更多内容


Say we have following code and when break we want to break out of the inner and outer loop instead of just the inner loop and go directly to blablabla. How can we do this in C++?

for (int i = 0; i < m; i++) {
    for (int j = 0; j < n; j++) {
         if (some condition) {
             // Do something and break...
             break; // Breaks out of the inner loop
         }
    }
}

blablabla
...

解决方案

"Go directly to [...]" sound like a perfect job for goto. And it is !

for (int i = 0; i < m; i++) {
    for (int j = 0; j < n; j++) {
         if (some condition) {
             // Do something and break...
             goto afterLoop; // Breaks out of both loops
         }
    }
}
afterLoop:
// More stuff

这篇关于在C ++中打破嵌套循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆