Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do (c++) vectors shrink after elements are removed?

Vectors double their size each time they run out of space when adding an element, but what about when you remove elements? say you added 800 elements to an array, and on the addition of that 800th element, the vector doubles its size to be able to hold 1600 elements. Now what if you start taking away elements to the point that its only holding say 5 or 10 elements?

will it recognize that the vector is much smaller than half the size of the space reserved for future elements and reserve less space?

like image 958
Charles Hetterich Avatar asked Nov 12 '14 01:11

Charles Hetterich


People also ask

Does the size of a vector change when elements are removed?

Array. The size of the vector changes automatically as elements are inserted or removed. The size of the array is fixed; you cannot change it after initializing its size once.

How do you reduce the size of a vector?

The C++ function std::vector::resize() changes the size of vector. If n is smaller than current size then extra elements are destroyed. If n is greater than current container size then new elements are inserted at the end of vector. If val is specified then new elements are initialed with val.

Does Pop_back reduce size?

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.

Does erase change vector capacity?

No. That's implied by the fact that iterators, pointers and references prior to the point of erase remain valid. Reducing the capacity would require a reallocation.


1 Answers

Vectors do not decrease in capacity when removing elements! This is to allow future elements to be added efficiently into the existing buffer.

like image 192
Neil Kirk Avatar answered Sep 24 '22 07:09

Neil Kirk