C++ 哪个更好“for(int i = 0; i != 5; ++i)”或“for(int i = 0; i <= 5; i++)”?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4733869/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
which is better "for(int i = 0; i != 5; ++i)" or "for(int i = 0; i <= 5; i++)"?
提问by Sulla
which is better for(int i = 0; i != 5; ++i)
or for(int i = 0; i <= 5; i++)
?
这是更好的for(int i = 0; i != 5; ++i)
还是for(int i = 0; i <= 5; i++)
?
Please explain the rationale, if possible.
如果可能,请解释理由。
I read somewhere that != operator is better than comparison operators. also pre-increment operator is better than post-increment operator, since it doesn't require any temporary variable to store the intermediate value.
我在某处读到 != 运算符比比较运算符更好。前增量运算符也比后增量运算符更好,因为它不需要任何临时变量来存储中间值。
Is there any better form of for loop than these two?
有没有比这两个更好的 for 循环形式?
p.s: I use the former one as suggested by one of the sources, which i don't remember now.
ps:我按照其中一位消息来源的建议使用了前一种,我现在不记得了。
回答by peoro
There are at least two differences:
至少有两点不同:
the first one will iterate 5 times (from 0 to 4), while the second one will iterate 6 times (from 0 to 5).
This is a logic difference, and it depends on what you need to do.
If what you meant for the second example was
i<=4
(versusi!=5
) you shouldn't bother: any compiler will always be able to optimize such a trivial expression even with optimizations turned off.the second difference is the use of operator
++
: in a case you use the prefix version, while in the other the postfix version.This doesn't make difference for native types, but could do some difference with user defined types (ie classes, structs, enums, ...), since the user could overload the operator, and the postfix one (
var ++
) could be a little slower sometimes.
第一个将迭代 5 次(从 0 到 4),而第二个将迭代 6 次(从 0 到 5)。
这是逻辑上的差异,这取决于您需要做什么。
如果您对第二个示例的意思是
i<=4
(相对于i!=5
),则不必费心:即使关闭了优化,任何编译器也始终能够优化这样一个微不足道的表达式。第二个区别是运算符的使用
++
:在一种情况下您使用前缀版本,而在另一种情况下使用后缀版本。这对本机类型没有影响,但可能会对用户定义的类型(即类、结构、枚举等)产生一些影响,因为用户可能会重载运算符,而后缀 (
var ++
) 可能有点有时更慢。
回答by jcoder
Using "i < 5" would be the form most people would expect to see on a for loop based on common usage. There is nothing wrong of course with "i != 5" or "i <= 5" (expect they'll give different loop counts) but if I see either of those forms I have to stop and think because it's not the most common form.
使用“i < 5”将是大多数人希望在基于常见用法的 for 循环中看到的形式。“i != 5”或“i <= 5”当然没有错(期望它们会给出不同的循环计数)但是如果我看到这两种形式中的任何一种,我必须停下来思考,因为它不是最常见的形式。
So I would always write "i < 5" unless there was a strong reason to do otherwise
所以我总是写“i < 5”,除非有充分的理由不这样做
回答by davep
Generally, you should write for PEOPLE not the computer.
通常,您应该为 PEOPLE 而不是计算机写作。
The "for(i = 0; i < 5; i++)" form makes it very clear that the valid range is "0 through 4" and nothing else.
“for(i = 0; i < 5; i++)”形式清楚地表明有效范围是“0 到 4”,没有别的。
And as other people said, this form make sure that funny code in the loop is much less likely to cause an infinite loop. And as other people have said, use the form that reflects what you mean.
正如其他人所说,这种形式确保循环中有趣的代码不太可能导致无限循环。正如其他人所说,请使用反映您的意思的表格。
Note that "less than" is the idiom commonly used in c (which means more programmers will expect that). That's another reason to prefer the "for(i = 0; i < 5; i++)" form.
请注意,“小于”是 c 中常用的习语(这意味着更多的程序员会期望)。这是更喜欢“for(i = 0; i < 5; i++)”形式的另一个原因。
回答by MadMan
which is better for(int i = 0; i != 5; ++i) or for(int i = 0; i <= 5; i++)?
哪个更适合(int i = 0; i != 5; ++i) 或 for(int i = 0; i <= 5; i++)?
the 2nd one since its a Bolian Operator, then this for(int i = _; i <= __ or etc ; i++ increment )? --> it's widely used as now a days even when are beginners in programming.
第二个,因为它是一个 Bolian 运算符,那么这个 for(int i = _; i <= __ or etc ; i++ increment )?--> 即使是编程初学者,它现在也被广泛使用。
回答by Bram
My teacher in the C++ language told me to use the canonical forms: for(int x=0; x != 5; ++i)
我的 C++ 语言老师告诉我使用规范形式: for(int x=0; x != 5; ++i)
Thou the other works just fine but suppose you want to use the loop on a iterator. Then <= does not has to be properly defined and a postfix inc might make your program spend alot of time copying objects.
你另一个工作得很好,但假设你想在迭代器上使用循环。然后 <= 不必正确定义,后缀公司可能会使您的程序花费大量时间复制对象。
So he made us use the forms
所以他让我们使用表格
for(int i=begin; x != end; ++i)
and for(int i=begin; end != i--; )
for(int i=begin; x != end; ++i)
和 for(int i=begin; end != i--; )
回答by Tony Delroy
You should use whichever of <
, <=
, !=
etc. best expresses your application logic, but if there's no reason to prefer any particular style, then be consistent. In informing that decision, the <
and !=
operators have the advantage of allowing comparisons between 0-based indices and sizeof
or STL-style size
/ length
values, as in:
您应该使用取其<
,<=
,!=
等最能表达你的应用程序逻辑,但如果我们没有理由没有特别喜欢的风格,然后是一致的。在通知该决定时,<
and!=
运算符具有允许在基于 0 的索引和/sizeof
或 STL 样式size
/length
值之间进行比较的优势,如下所示:
for (size_t i = 0; i < my_vector.size(); ++i)
...
The <
and <=
operators sometimes guard against incrementing past the terminating value (if you've got another condition inside the loop under which you increment/add-to i
, or there's some floating point rounding/representation disparity). Not often actually significant, but saving an occasional bug is better than nothing.
在<
与<=
运营商有时防范递增过去的结尾值(如果你有一个你增量/添加到内循环的另一个条件i
,或有一些浮点四舍五入/代表性的差距)。通常实际上并不重要,但偶尔保存一个错误总比没有好。
Given '<' is the intersection of these two sets, it's a popular choice. To my mind, <
also communicates the states under which the loop runs... a more positive assertion rather than the !=
style. In general, negative assertions are discouraged in programming (e.g. bool invalid
is more complicated to get your head around reliably than bool valid
, especially in complex boolean expression and when double-negatives are introduced).
鉴于 '<' 是这两个集合的交集,这是一个流行的选择。在我看来,<
还传达了循环运行的状态……更积极的断言而不是!=
风格。通常,在编程中不鼓励否定断言(例如,bool invalid
比 可靠地了解您的头脑更复杂bool valid
,尤其是在复杂的布尔表达式中和引入双重否定时)。
This is of course for numeric types. Other types may imply other styles... for example, use of != sentinel
. I prefer to have the choice of operator help document these usage implications of the type, though that's a personal choice and arguably redundant.
这当然适用于数字类型。其他类型可能暗示其他样式……例如,使用!= sentinel
. 我更喜欢选择操作符帮助来记录该类型的这些使用含义,尽管这是个人选择并且可以说是多余的。
Otherwise, preincrement can be more efficient for complicated types than post- as it avoids a temporary.
否则,对于复杂类型,preincrement 可能比 post- 更有效,因为它避免了临时。
回答by Miles Vorkosigan
The condition != is simply faster than both < and (even more) <= otherwise it is just question of taste, though one needs to be careful of possible infinite loops.
条件 != 比 < 和(甚至更多)<= 都快,否则这只是品味问题,尽管需要小心可能的无限循环。