在C ++中用for(; condition;)替换while(condition)的任何原因? [英] Any reason to replace while(condition) with for(;condition;) in C++?
问题描述
看起来像
while( condition ) {
//do stuff
}
完全等同于
for( ; condition; ) {
//do stuff
}
是否有理由使用后者而不是前者?
Is there any reason to use the latter instead of the former?
推荐答案
没有好理由,据我所知。
There's no good reason as far as I know. You're intentionally misleading people by using a for-loop that doesn't increment anything.
更新:
根据OP对该问题的评论,我可以推测你如何在实际代码中看到这样的结构。我已经看过(和使用)这之前:
Based on the OP's comment to the question, I can speculate on how you might see such a construct in real code. I've seen (and used) this before:
lots::of::namespaces::container::iterator iter = foo.begin();
for (; iter != foo.end(); ++iter)
{
// do stuff
}
但是这是我离开一个for循环。也许你的项目有一个循环,看起来像一次。如果你添加在循环中删除容器元素的代码,你可能必须仔细控制 iter
是否递增。这可能会导致代码看起来像这样:
But that's as far as I'll go with leaving things out of a for-loop. Perhaps your project had a loop that looked like that at one time. If you add code that removes elements of a container in the middle of the loop, you likely have to control carefully how iter
is incremented. That could lead to code that looks like this:
for (; iter != foo.end(); )
{
// do stuff
if (condition)
{
iter = foo.erase(iter);
}
else
{
++iter;
}
}
但是,这不是没有借口,需要将其更改为while循环。
However, that's no excuse for not taking the five seconds needed to change it into a while-loop.
这篇关于在C ++中用for(; condition;)替换while(condition)的任何原因?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!