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

前端 未结 13 1446
爱一瞬间的悲伤
爱一瞬间的悲伤 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:19

    The first form (inside the for loop) is better if the iterator is not needed after the for loop. It limits its scope to the for loop.

    I seriously doubt that there is any efficiency gain either way. It can also be made more readable with a typedef.

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

    I would recommend shorter names ;-)

提交回复
热议问题