情况:你有一个嵌套循环,你需要突破它。
让我们看看这个经典的例子(经典,因为它来自Goto Considered Harmful Considered Harmful):给定一个二维NxN
方形整数矩阵X
,找到没有零的第一行。
我将通过几种不同语言解决这个问题的方法。我想我应该从 的编写方式开始,但不是。
//using "chained breaks"
for(int i=0;i<N;i++){
for(int j=0;j<N;j++){
if( X[i][j] == 0 ){
//this row isn't non-zero, so go to the next row
break continue;
//break out of the inner loop and continue the outer loop
}
}
//if we get to here, we know this row doesn't have zeroes
return i;
}
return -1; //failure; exact val doesn't matter for this question
C及其主要忠实的衍生品:
//goto
for(int i=0;i<N;i++){
for(int j=0;j<N;j++){
if( X[i][j] == 0 ){
//this row isn't non-zero, so go to the next row
goto next; //skip past the return
}
}
//if we get to here, we know this row doesn't have zeroes
return i;
label next;
}
return -1; //failure; exact val doesn't matter for this question
爪哇:
//labeled loops and labeled break/continue
outer: for(int i=0;i<N;i++){
for(int j=0;j<N;j++){
if( X[i][j] == 0 ){
//this row isn't non-zero, so go to the next row
continue outer; //go to the next row
}
}
//if we get to here, we know this row doesn't have zeroes
return i;
}
return -1; //failure; exact val doesn't matter for this question
PHP:
//this PHP may be wrong, it's been a while
for($i=0;$i<$N;$i++){
for($j=0;$j<$N;$j++){
if( $X[$i][$j] == 0 ){
//this row isn't non-zero, so go to the next row
continue 2;
//continue the outer loop
}
}
//if we get to here, we know this row doesn't have zeroes
return $i;
}
return -1; //failure; exact val doesn't matter for this question
使用旗帜:
//using a flag
for(int i=0;i<N;i++){
bool foundzero = false;
for(int j=0;j<N;j++){
if( X[i][j] == 0 ){
//this row isn't non-zero, so go to the next row
foundzero = true;
break; //go to the next row
}
}
//if we get to here, we know this row doesn't have zeroes
if(!foundzero)
return i;
}
return -1; //failure; exact val doesn't matter for this question
将内循环导出到函数:
//using a function call
for(int i=0;i<N;i++){
if(haszero(X[i],N))
return i;
}
return -1; //failure; exact val doesn't matter for this question
//and the haszero function
bool haszero(int arr[], int N){
for(int i=0;i<N;i++){
if( arr[i] == 0 ){
return false;
}
}
return true;
}
现在,所有这些工作,但有些功能调用开销(如果语言想要允许深度循环则很糟糕),标志(对某些人来说令人反感或不直观),goto
(比你可能需要的更强大) ),或奇怪的语法(Java的愚蠢)。
那么为什么语言没有break break
,break continue
,break break continue
等? (continue break
毫无意义,因为它意味着进入下一次迭代然后离开它。将这类内容添加到语言中是否存在问题?