Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is deleting the tail of a vector (through erase) memory efficient?

Tags:

c++

stl

When doing v.erase(some_iterator);

Are implementations smart enough to not do any reallocations/bytes-copying since we could just update the size? (Unlike when erasing strictly inner elements.)

like image 836
user2370139 Avatar asked May 16 '17 11:05

user2370139


People also ask

Does erase reduce size of vector?

All the elements of the vector are removed using clear() function. erase() function, on the other hand, is used to remove specific elements from the container or a range of elements from the container, thus reducing its size by the number of elements removed.

Does vector erase change capacity?

King Of course the size have to be changed since an element is removed, but the capacity doesn't have to change.

What does vector erase do?

vector::eraseErases 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.

Does vector erase shift?

Logically yes, as a vector is a dynamic array of element. You delete one, then everything that follows is moved. In the same manner, the total length of the vector will decrease as you erase elements.


1 Answers

Erasing from an std::vector does not invalidate iterators and references to the elements before the first erased element.

So if you delete only the last element, it is guaranteed that all of the other elements stay where they are, they are not moved around or copied.

However, note that erasing from an std::vector generally only changes its size, not its capacity, so the memory the old objects lived in is still owned by the vector. This is for performance reasons and nothing to worry about (unless you run out of RAM).

Also, the erased objects are of course properly destructed, so if they are not trivially destructable, their destructors must be run in addition to adjusting the vector's size.

like image 157
Baum mit Augen Avatar answered Oct 23 '22 15:10

Baum mit Augen