C++ STL Vectors: Get iterator from index?

前端 未结 5 923
伪装坚强ぢ
伪装坚强ぢ 2020-12-07 07:36

So, I wrote a bunch of code that accesses elements in an stl vector by index[], but now I need to copy just a chunk of the vector. It looks like vector.insert(pos, fir

5条回答
  •  生来不讨喜
    2020-12-07 08:05

    way mentioned by @dirkgently ( v.begin() + index ) nice and fast for vectors

    but std::advance( v.begin(), index ) most generic way and for random access iterators works constant time too.

    EDIT
    differences in usage:

    std::vector<>::iterator it = ( v.begin() + index );
    

    or

    std::vector<>::iterator it = v.begin();
    std::advance( it, index );
    

    added after @litb notes.

提交回复
热议问题