退出循环 [英] Exiting from loop

查看:62
本文介绍了退出循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有嵌套循环,例如:


for(...)for(...)for(...){/ * exit here * /}


我需要从那里退出^。


使用异常或转到或其他方法更好吗?

解决方案

vineoff写道:

如果我有嵌套循环,如:

for(...)for(..)for(...){/ * exit here * /}

我需要从那里退出^。

是否更好地使用异常或转到或其他方法?




goto。


vineoff写道:< blockquote class =post_quotes>
如果我有嵌套循环,如:

for(...)for(...)for(...){/ * exit这里* /}

我需要从那里退出^。

使用异常或转到或其他一些方法更好吗?




创建一个只包含嵌套循环的函数并且

从最里面循环中的该函数返回。


(是:它是一种goto,没有明确的goto)
< br $>
-

Karl Heinz Buchegger
kb ***** *@gascad.at


Tatu Portin写道:

vineoff写道:

如果我'我有嵌套循环如:

for(...)for(...)for(...){/ * exit here * /}

我需要从那里退出^。

使用异常或goto或其他方法更好吗?



goto。




我发现有一个变量可以更清楚地表明是时候退出:


bool done = false;

for(int i = 0;完成&&我< 10; ++ i)

{

for(int j = 0;!done&& j< 10; ++ j)

{

for(int k = 0;!done&& k< 10; ++ k)

{

if (k == 5)//一些虚拟退出条件

{

done = true;

继续; //或休息;

}

}

}

}


一般情况下,你不应该使用例外,除非条件是,b $ b,b,例外。 IOW,不要使用异常作为替代打破

并在没有实际错误的情况下继续(但是定义了

)。


干杯! --M


If I''m having nested loops like:

for (...) for (..) for (...) { /* exit here */ }

and I need to exit from there ^ .

Is it better to use exceptions or goto or some other method?

解决方案

vineoff wrote:

If I''m having nested loops like:

for (...) for (..) for (...) { /* exit here */ }

and I need to exit from there ^ .

Is it better to use exceptions or goto or some other method?



goto.


vineoff wrote:


If I''m having nested loops like:

for (...) for (..) for (...) { /* exit here */ }

and I need to exit from there ^ .

Is it better to use exceptions or goto or some other method?



Create a function which holds only the nested loops and
return from that function in the innermost loop.

(Yes: it is a sort of goto, without an explicite goto)

--
Karl Heinz Buchegger
kb******@gascad.at


Tatu Portin wrote:

vineoff wrote:

If I''m having nested loops like:

for (...) for (..) for (...) { /* exit here */ }

and I need to exit from there ^ .

Is it better to use exceptions or goto or some other method?



goto.



I find it clearer to have a variable to indicate that it is time to
exit:

bool done = false;
for( int i=0; !done && i < 10; ++i )
{
for( int j=0; !done && j < 10; ++j )
{
for( int k=0; !done && k < 10; ++k )
{
if( k == 5 ) // Some dummy exit condition
{
done = true;
continue; // or break;
}
}
}
}

In general, you should not use exceptions unless the condition is,
well, exceptional. IOW, don''t use exceptions as an alternative to break
and continue when there is not actually an error (however that is
defined).

Cheers! --M


这篇关于退出循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆