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

后端 未结 9 1033
轻奢々
轻奢々 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    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.

提交回复
热议问题