lee*_*ewz 5 loops language-design structured-programming
情况:你有一个嵌套循环,你需要突破它.
让我们来看看这个经典的例子(经典,因为它来自Goto Consideredred 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
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
Java的:
//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
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
使用标志:
//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
Run Code Online (Sandbox Code Playgroud)
将内循环导出到函数:
//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;
}
Run Code Online (Sandbox Code Playgroud)
现在,所有这些工作,但一些有函数调用开销(如果语言想要允许深度循环那么糟糕),标志(对某些人来说是令人反感或不直观的),goto(比你可能需要的更强大),或者奇怪的语法(Java的愚蠢) ).
那么,为什么不用语言有break break,break continue,break break continue,等?(continue break毫无意义,没意义,因为它意味着进入下一次迭代然后离开它).将这类内容添加到语言中是否存在问题?