是Iterator初始化里面for循环认为坏风格

是Iterator初始化里面for循环认为坏风格

本文介绍了是Iterator初始化里面for循环认为坏风格,为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通常你会发现这样的STL代码:

Typically you will find STL code like this:

for (SomeClass::SomeContainer::iterator Iter = m_SomeMemberContainerVar.begin(); Iter != m_SomeMemberContainerVar.end(); ++Iter)
{
}

但是我们实际上有这样写的建议:

But we actually have the recommendation to write it like this:

SomeClass::SomeContainer::iterator Iter = m_SomeMemberContainerVar.begin();
SomeClass::SomeContainer::iterator IterEnd = m_SomeMemberContainerVar.end();
for (; Iter != IterEnd; ++Iter)
{
}

如果您担心范围限制,请添加括号括号:

If you're worried about scoping, add enclosing braces:

{
    SomeClass::SomeContainer::iterator Iter = m_SomeMemberContainerVar.begin();
    SomeClass::SomeContainer::iterator IterEnd = m_SomeMemberContainerVar.end();
    for (; Iter != IterEnd; ++Iter)
    {
    }
}

这应该能够提高速度和效率,特别是如果你是编程控制台,因为.end()函数在循环的每次迭代都不被调用。我只是把性能改进是理所当然的,这听起来很合理,但我不知道多少,它当然取决于容器的类型和实际使用的STL实现。但是使用这种风格了几个月了,我实际上更喜欢它在第一个。

This is supposed to give a speed and efficiency gain, especially if you are programming consoles, because the .end() function is not called on each iteration of the loop. I just take the performance improvement for granted, it sounds reasonable but i don't know how much and it certainly depends on the type of container and actual STL implementation in use. But having used this style for a couple months now i actually prefer it over the first anyway.

原因是可读性:for行是整洁和整洁。在实际生产代码中使用限定符和成员变量,如果您使用第一个示例中的样式,则很容易使用真正行。这就是为什么我有意在这个例子中有一个水平滚动条,只是为了看到我在说什么。 ;)

The reason being readability: the for line is neat and tidy. With qualifiers and member variables in real production code it is quite easy to have really long for lines if you use the style in the first example. That's why i intentionally made it to have a horizontal scrollbar in this example, just so you see what i'm talking about. ;)

另一方面,你突然将Iter变量引入到for循环的外部范围。但是,至少在我工作的环境中,Iter将在外部范围内访问,即使在第一个示例中。

On the other hand, you suddenly introduce the Iter variables to the outer scope of the for loop. But then, at least in the environment i work in, the Iter would have been accessible in the outer scope even in the first example.

你对此有什么看法?

推荐答案

如果你把你的代码包装到正确的行,则内联表单将同样可读。此外,您应该始终将 iterEnd = container.end()作为优化:

If you wrap your code into lines properly, the inline form would be equally readable. Besides, you should always do the iterEnd = container.end() as an optimization:

for (SomeClass::SomeContainer::iterator Iter = m_SomeMemberContainerVar.begin(),
    IterEnd = m_SomeMemberContainerVar.end();
    Iter != IterEnd;
    ++Iter)
{
}

更新:修正每个paercebal建议。

Update: fixed the code per paercebal's advice.

这篇关于是Iterator初始化里面for循环认为坏风格,为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 18:02