5

情况:你有一个嵌套循环,你需要打破它。

让我们来看这个经典的例子(经典,因为它来自Goto 被认为是有害的,被认为是有害的):给定一个二维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几乎没有意义,因为这意味着进入下一个迭代然后离开它)。在语言中添加这种东西有问题吗?

4

0 回答 0