Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 936
sgtHale Avatar asked Jul 28 '14 21:07

sgtHale


People also ask

How do you remove an element from the end of a vector?

pop_back() function is used to pop or remove elements from a vector from the back. The value is removed from the vector from the end, and the container size is decreased by 1.

What does erase () in vector do?

vector::erase() erase() function is used to remove elements from a container from the specified position or range.

What happens when we erase a element in the vector?

vector::erase Erases the specified elements from the container. 1) Removes the element at pos. 2) Removes the elements in the range [first, last) . Invalidates iterators and references at or after the point of the erase, including the end() iterator.


1 Answers

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.

like image 75
StilesCrisis Avatar answered Nov 15 '22 05:11

StilesCrisis