如果我有一个嵌套在另一个循环中的for循环,我如何才能以最快的方式有效地从两个循环(内部和外部)中出来?

我不想必须使用布尔值然后必须说转到另一个方法,而只是在外部循环之后执行第一行代码。

有什么又快又好的方法呢?

我在想异常并不便宜/只应该在真正异常的情况下抛出等等。因此,从性能的角度来看,我不认为这个解决方案是好的。

我不认为利用。net中的新特性(anon方法)来做一些非常基础的事情是正确的。


当前回答

是否有可能将嵌套的for循环重构为私有方法?这样你就可以简单地从方法中“返回”以退出循环。

其他回答

我就设个旗子。

var breakOuterLoop = false;
for (int i = 0; i < 30; i++)
{
    for (int j = 0; j < 30; j++)
    {
        if (condition)
        {
            breakOuterLoop = true;
            break;
        }
    }
    if (breakOuterLoop){
        break;
    }
}

我见过很多用break的例子,但没有一个用continue的。

它仍然需要在内部循环中使用某种标志:

while( some_condition )
{
    // outer loop stuff
    ...

    bool get_out = false;
    for(...)
    {
        // inner loop stuff
        ...

        get_out = true;
        break;
    }

    if( get_out )
    {
        some_condition=false;
        continue;
    }

    // more out loop stuff
    ...

}

自从几十年前我第一次看到C语言中的break,这个问题就一直困扰着我。我希望一些语言增强会有一个扩展打破,这样工作:

break; // our trusty friend, breaks out of current looping construct.
break 2; // breaks out of the current and it's parent looping construct.
break 3; // breaks out of 3 looping constructs.
break all; // totally decimates any looping constructs in force.

这里没有提到的另一种方法是将双循环合并为产品上的单个循环,它既干净又不依赖于更新的。net特性。然后在循环内部,计数器的值可以使用简单的数学计算:

int n; //set to max of first loop
int m; //set to max of second loop

for (int k = 0; k < n * m; k++)
{
    //calculate the values of i and j as if there was a double loop
    int i = k / m;
    int j = k % m;
    
    if(exitCondition)
    {
        break;
    }
}

最干净、最短、最可重用的方法是自调用匿名函数:

没有转到 没有标签 没有临时变量 没有命名函数

用匿名方法,比上面的答案短一行。

new Action(() =>
{
    for (int x = 0; x < 100; x++)
    {
        for (int y = 0; y < 100; y++)
        {
            return; // exits self invoked lambda expression
        }
    }
})();
Console.WriteLine("Hi");