C++ STL: Which method of iteration over a STL container is better?

后端 未结 9 990
轻奢々
轻奢々 2020-12-09 11:43

This may seem frivolous to some of you, but which of the following 2 methods of iteration over a STL container is better? Why?



        
相关标签:
9条回答
  • 2020-12-09 12:19

    Some more advantages of method 0:

    • if you move from vector to another container the loop remains the same,
    • easy to move from iterator to const_iterator if you need,
    • when c++0x will arive, auto typing will reduce some of the code clutter.

    The main disadvantage is that in many cases you scan two containers, in which case an index is cleaner than keeping two iterators.

    0 讨论(0)
  • 2020-12-09 12:21

    A possibility not considered above: depending on the details of "Do something", one can have method 0 and method 1 simultaneously, you don't have to choose:

    for (auto i = elemVec.begin(), ii = 0; ii < elemVec.size(); ++i, ++ii)
    {
        // Do something with either the iterator i or the index ii
    }
    

    This way, finding the index or accessing the corresponding member are both obtained with trivial complexity.

    0 讨论(0)
  • 2020-12-09 12:22

    The following method of iteration over a standard library container is best.

    Use c++11 (and beyond)'s range-based for-loop with the auto specifier:

    // Method 2
    for (auto& e: elemVec)
    {
        // Do something with e...
    }
    

    This is similar to your Method 0 but requires less typing, less maintenence and works with any container compatible with std::begin() and std::end(), including plain-old arrays.

    0 讨论(0)
提交回复
热议问题