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.)
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.
King Of course the size have to be changed since an element is removed, but the capacity doesn't have to change.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With