What is the difference between accessing vector elements using an iterator vs an index?

前端 未结 4 2107
名媛妹妹
名媛妹妹 2021-02-19 09:29

What advantages are there in accessing vector elements using an iterator vs an index?

4条回答
  •  甜味超标
    2021-02-19 09:52

    I say its portability across containers.

    If you write a code using vectors and use index to iterate then the code cannot be changed to other containers easily later .

    typedef std::vector myContainer; //only change here for std::list 
    
    for ( myContainer::iterator iter = actualContainer.begin();
          iter != actualContainer.end(); 
          ++iter)
    {}
    

    In the above code if you want to change from vector to list, it is very easily possible. If you had used the index then it won't be possible.

    Otherwise since the vector uses random access iterators it should be the same. ( index or iterator anything is ok)

提交回复
热议问题