C++ STL Vectors: Get iterator from index?

前端 未结 5 928
伪装坚强ぢ
伪装坚强ぢ 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: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 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]);
    

提交回复
热议问题