Is Iterator initialization inside for loop considered bad style, and why?

前端 未结 13 1445
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-05 19:37

Typically you will find STL code like this:

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


        
13条回答
  •  不思量自难忘°
    2021-02-05 20:10

    I don't have a particularly strong opinion one way or the other, though iterator lifetime would lean me toward the for-scoped version.

    However, readability may be an issue; that can be helped by using a typedef so the iterator type is a bit more manageable:

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

    Not a huge improvement, but a bit.

提交回复
热议问题