循环中的最后一个元素是否值得单独处理? [英] Does the last element in a loop deserve a separate treatment?

查看:27
本文介绍了循环中的最后一个元素是否值得单独处理?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

复习的时候,有时会遇到这样的循环:

When reviewing, I sometimes encounter this kind of loop:

i = begin
while ( i != end ) {    
   // ... do stuff
   if ( i == end-1 (the one-but-last element) ) {
      ... do other stuff
   }
   increment i
}

那我问一个问题:你会写这个吗?

Then I ask the question: would you write this?

i = begin
mid = ( end - begin ) / 2 // (the middle element)
while ( i != end ) {    
   // ... do stuff
   if ( i > mid ) {
      ... do other stuff
   }
   increment i
}

在我看来,这违背了编写循环的初衷:循环是因为每个元素都有一些共同的事情要做.使用此构造,对于某些元素,您可以做一些不同的事情.因此,我得出的结论是,您需要为这些元素创建一个单独的循环:

In my opinion, this beats the intention of writing a loop: you loop because there is something common to be done for each of the elements. Using this construct, for some of the elements you do something different. So, I conclude, you need a separate loop for those elements:

i = begin
mid = ( end - begin ) / 2 //(the middle element)
while ( i != mid ) {    
   // ... do stuff
   increment i
}

while ( i != end ) {
   // ... do stuff
   // ... do other stuff
   increment i
}

现在我什至在 SO 上看到了一个 问题 关于如何以一种很好的方式编写 if 子句......我很伤心:这里有些不对劲.

Now I even saw a question on SO on how to write the if-clause in a nice way... And I got sad: something isn't right here.

我错了吗?如果是这样,在编码时将循环体与特殊情况(您预先知道)混在一起有什么好处?

Am I wrong? If so, what's so good about cluttering the loop body with special cases, which you are aware of upfront, at coding time?

推荐答案

@xtofl,

我同意你的担忧.

数百万次我遇到了类似的问题.

Million times I encountered similar problem.

开发人员为第一个或最后一个元素添加特殊处理.

Either developer adds special handling for first or for last element.

在大多数情况下,只需要从 startIdx + 1endIdx - 1 元素开始循环,甚至将一个长循环分成多个较短的循环.

In most cases it is worth to just loop from startIdx + 1 or to endIdx - 1 element or even split one long loop into multiple shorter loops.

在极少数情况下,不可能拆分循环.

In a very rare cases it's not possible to split loop.

在我看来不常见的事情应该尽可能在循环之外处理.

In my opinion uncommon things should be handled outside of the loop whenever possible.

这篇关于循环中的最后一个元素是否值得单独处理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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