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

前端 未结 13 1605
爱一瞬间的悲伤
爱一瞬间的悲伤 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条回答
  •  猫巷女王i
    2021-02-05 20:05

    Another alternative is to use a foreach macro, for example boost foreach:

    BOOST_FOREACH( ContainedType item, m_SomeMemberContainerVar )
    {
       mangle( item );
    }
    

    I know macros are discouraged in modern c++, but until the auto keyword is widely available this is the best way I've found to get something that is concise and readable, and still completely typesafe and fast. You can implement your macro using whichever initialization style gets you better performance.

    There's also a note on the linked page about redefining BOOST_FOREACH as foreach to avoid the annoying all caps.

提交回复
热议问题