C++ STL Vectors: Get iterator from index?

前端 未结 5 826
伪装坚强ぢ
伪装坚强ぢ 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 07:40

    Try this:

    vector<Type>::iterator nth = v.begin() + index;
    
    0 讨论(0)
  • 2020-12-07 07:44

    Also; auto it = std::next(v.begin(), index);

    Update: Needs a C++11x compliant compiler

    0 讨论(0)
  • 2020-12-07 07:45

    Actutally std::vector are meant to be used as C tab when needed. (C++ standard requests that for vector implementation , as far as I know - replacement for array in Wikipedia) For instance it is perfectly legal to do this folowing, according to me:

    int main()
    {
    
    void foo(const char *);
    
    sdt::vector<char> vec;
    vec.push_back('h');
    vec.push_back('e');
    vec.push_back('l');
    vec.push_back('l');
    vec.push_back('o');
    vec.push_back('/0');
    
    foo(&vec[0]);
    }
    

    Of course, either foo must not copy the address passed as a parameter and store it somewhere, or you should ensure in your program to never push any new item in vec, or requesting to change its capacity. Or risk segmentation fault...

    Therefore in your exemple it leads to

    vector.insert(pos, &vec[first_index], &vec[last_index]);
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-07 08:05

    Or you can use std::advance

    vector<int>::iterator i = L.begin();
    advance(i, 2);
    
    0 讨论(0)
提交回复
热议问题