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

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

    It may make for disjointed code, but I also like to pull it out to a separate function, and pass both iterators to it.

    doStuff(coll.begin(), coll.end())
    

    and have..

    template
    void doStuff(InIt first, InIt last)
    {
       for (InIt curr = first; curr!= last; ++curr)
       {
           // Do stuff
       }
     }
    

    Things to like:

    • Never have to mention the ugly iterator type (or think about whether it's const or not-const)
    • If there is gain from not calling end() on each iteration, I'm getting it

    Things to not like:

    • Breaks up the code
    • Overhead of additional function call.

    But one day, we'll have lambdas!

提交回复
热议问题