有什么理由在 C++ 中用 for(;condition;) 替换 while(condition)?

2023-08-27C/C++开发问题
1

本文介绍了有什么理由在 C++ 中用 for(;condition;) 替换 while(condition)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

看起来像

while( condition ) {
    //do stuff
}

完全等同于

for( ; condition; ) {
    //do stuff
}

是否有任何理由使用后者而不是前者?

Is there any reason to use the latter instead of the former?

推荐答案

据我所知,没有好的理由.您通过使用不增加任何内容的 for 循环故意误导人们.

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;
    }
}

然而,这不是不花 5 秒时间将其更改为 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)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

无法访问 C++ std::set 中对象的非常量成员函数
Unable to access non-const member functions of objects in C++ std::set(无法访问 C++ std::set 中对象的非常量成员函数)...
2024-08-14 C/C++开发问题
17

从 lambda 构造 std::function 参数
Constructing std::function argument from lambda(从 lambda 构造 std::function 参数)...
2024-08-14 C/C++开发问题
25

STL BigInt 类实现
STL BigInt class implementation(STL BigInt 类实现)...
2024-08-14 C/C++开发问题
3

使用 std::atomic 和 std::condition_variable 同步不可靠
Sync is unreliable using std::atomic and std::condition_variable(使用 std::atomic 和 std::condition_variable 同步不可靠)...
2024-08-14 C/C++开发问题
17

在 STL 中将列表元素移动到末尾
Move list element to the end in STL(在 STL 中将列表元素移动到末尾)...
2024-08-14 C/C++开发问题
9

为什么禁止对存储在 STL 容器中的类重载 operator&()?
Why is overloading operatoramp;() prohibited for classes stored in STL containers?(为什么禁止对存储在 STL 容器中的类重载 operatoramp;()?)...
2024-08-14 C/C++开发问题
6