sgtHale
sgtHale

Reputation: 1547

C++ erasing part of the end of a vector without reallocation

Looking through the C++ vector documents, pop_back() is a function that will not cause a reallocation of the vector's data. However, this only works for removing one member of the vector. I am trying to find a way to erase multiple members from the end of a vector. Originally I thought I would call pop_back() in a small for loop but I was wandering if there was a more convenient function that would do this for me?

Edit: The Cplusplus vector erase() reference is not as clear as it should be as pointed out by juanchopanza. It is why I originally discarded using erase(). Erase afterall, works well.

Upvotes: 6

Views: 2204

Answers (2)

Vlad from Moscow
Vlad from Moscow

Reputation: 311048

You can use member functions erase. The vector will not be reallocated because according to the C++ Standard, e.g. C++17 n4659 standard draft 26.3.11.5 [vector.modifiers] "vector modifiers":

iterator erase(const_iterator position);
iterator erase(const_iterator first, const_iterator last);

3 Effects: Invalidates iterators and references at or after the point of the erase.

The bold part of the quote means that the vector will not be reallocated.

Upvotes: 5

StilesCrisis
StilesCrisis

Reputation: 16290

Use vector::erase. It will not reallocate memory.

If your erased range does not extend to the end of the container, it WILL re-locate the end elements. That means the ending elements will be moved to their proper spot in memory which likely incurs a data copy. That is not the same as a re-allocation of the backing store. If your ending element is myVector.end(), no relocation will need to occur.

Upvotes: 8

Related Questions