c++c++11vectorstl

How to remove several elements from the end of std::vector?


Let's say I have a std::vector of integers:

std::vector<int> v;

v contains 100 elements, and I want to remove the last 10 elements. I can think of this solution:

v.erase(v.end() - 10, v.end());

Anything better?


Solution

  • You may try this:

    v.resize(v.size()-10);
    

    However, you need to benchmark it against your method. I am not sure it is better or even it may be exactly the same.

    You may also check the size before resizing:

    if(v.size()>=10){
        v.resize(v.size()-10);
    }
    

    EDIT:

    Resize removes elements at the end of the vectors: http://www.cplusplus.com/reference/vector/vector/resize/

    If n is smaller than the current container size, the content is reduced to its first n elements, removing those beyond (and destroying them).