如何优雅地退出多重循环
C++
1、 采用goto语句
goto语句虽然一直被大家所诟病,说破坏了代码的结构化特性,但是它也有自己的好处。
goto语句肯定不推荐大量使用,但是对于跳出多重循环还是特定方便,逻辑也比较清晰。
#include <iostream>
using namespace std;
int main(){
for(int i=1;i<10;i++){
for(int j=0;j<5;j++){
if(i==2 && j==3)
goto mark;
cout<<i<<" "<<j<<endl;
}
}
mark:
return 0;
}
结果:
2、 循环内多增加一个判断条件
对于退出循环不是特别迫切的,允许执行完本轮循环的,建议可以采用这种方式。
#include <iostream>
using namespace std;
int main(){
bool flag=true;
for(int i=1;i<10 && flag;i++){
for(int j=0;j<5 && flag;j++){
if(i==2 && j==3)
flag=false;
cout<<i<<" "<<j<<endl;
}
}
mark:
return 0;
}
结果:
我们可以看到这里比使用goto多了一个2 3
,因为我们不是立刻退出循环的,所以使用goto还是使用这个可以根据实际情况选择。
Java补充
1、break/continue tag
Java和C++大部分是类似的,但是Java是废弃了goto的,但是它提供了另外一个类似于goto的方法;
public class test2 {
public static void main(String[] args){
flag:for(int i=0;i<5;i++){
for(int j=0;j<5;j++){
if(i==2 && j==3){
break flag;
}
System.out.println(i+" "+j);
}
}
System.out.print("循环退出了");
}
}
结果:
0 0
0 1
0 2
0 3
0 4
1 0
1 1
1 2
1 3
1 4
2 0
2 1
2 2
循环退出了
Process finished with exit code 0
2、采用异常处理的方式
java的异常处理机制允许碰到异常直接跳到catch,不执行后面try语句,利用这个特性:
public class test2 {
public static void main(String[] args){
try{
flag:for(int i=0;i<5;i++){
for(int j=0;j<5;j++){
if(i==2 && j==3){
throw new Exception();
}
System.out.println(i+" "+j);
}
}
}catch (Exception e){
System.out.print("循环退出了");
}
}
}
结果:
0 0
0 1
0 2
0 3
0 4
1 0
1 1
1 2
1 3
1 4
2 0
2 1
2 2
循环退出了
Process finished with exit code 0