Assign part of a vector to itself using std::vector::assign()

前端 未结 2 755
借酒劲吻你
借酒劲吻你 2021-01-21 02:38

Let\'s say I have a vector(v1) of size 10. Now I want to only keep parts of the elements, using:
v1.assign(v1.begin() + 2, v1.begin() + 6);

What I\'

2条回答
  •  一整个雨季
    2021-01-21 03:05

    From the C++11 Standard:

    23.3.6.2 vector constructors, copy, and assignment

    template 
    void assign(InputIterator first, InputIterator last);
    

    11 Effects:

    erase(begin(), end());
    insert(begin(), first, last);
    

    In other words, don't use:

    v1.assign(v1.begin() + 2, v1.begin() + 6);
    

    By the time insert is called, first will be an invalid iterator.

提交回复
热议问题