1

The storage of the vector is handled automatically, being expanded and contracted as needed.

via cppreference

Can someone elaborate on the 'contracted' part? I thought a std::vector would always occupy the max capacity it reached even if we pop 99% of its elements, unless we call shrink_to_fit() explicitly or use the empty-swap idiom.

Suhail Khan
  • 190
  • 1
  • 1
  • 7
  • That does seem to be a little misleading. AFAIK, the only way to shrink a vector is to explicitly ask for it. That said, IIRC, the only requirement is that the iterators and references to elements in the vector not be invalidated if the are before the removed element. This I think allows for something like `realloc` to be used under the hood. – NathanOliver Jul 08 '21 at 14:15
  • I think this part is not to be taking too literally. For example `resize` is not allowed to shrink to smaller capcity even when the new size is less, but for example copying a vector does not necessarily preserve capacity afaik – 463035818_is_not_an_ai Jul 08 '21 at 14:16
  • 2
    See answers to [Can pop_back() ever reduce the capacity of a vector? (C++)](https://stackoverflow.com/q/23764785/10077). – Fred Larson Jul 08 '21 at 14:16
  • one way to read it is to regard the vectors capacity as being an abstract property of the vector, while the sentence is talking about "the storage of the vector". You can tell a vector to increase its capacity or to `shrink_to_fit` but you'll never directly get to expand or contract the underlying storage. Could also be that I am just interpreting too much into words ;) – 463035818_is_not_an_ai Jul 08 '21 at 14:23
  • "contracted as needed" is a pretty awful phrase, as contraction of a vector is _never needed_, by its own spec. Even `shrink_to_fit` [doesn't _need_ to shrink storage](https://en.cppreference.com/w/cpp/container/vector/shrink_to_fit). – Drew Dormann Jul 08 '21 at 19:54

0 Answers0