0

I am implementing my very own vector container in C++. To do so, firstly I am trying to fully understand how vectors work, and I've come across a problem while doing so.

According to C++ reference, vectors have both a size (the number of elements in the vector) and a capacity (the maximum amount of items the vector can store before reallocation is required). My first question is the following: when a vector is instanciated, how does the compiler ¨decide¨ the capacity of the vector? Is it a random number?

I have a second question as well. I have done several tests where I instanciate a vector with, let's say, X elements. In every single case, the capacity of the vector is X as well. However, if I pop back some elements, the size is reduced but the capacity remains the same. Does this always happen? I mean, are the capacity and size always the same when the vector is instanciated? If not, why do you think this is happening to me?

P.S. I compile with clang++

kubo
  • 221
  • 1
  • 8
  • 2
    please one question per question. – 463035818_is_not_an_ai Sep 15 '22 at 11:53
  • 3
    Regarding intial capacity of a vector, does [this](https://stackoverflow.com/questions/12271017/initial-capacity-of-vector-in-c) answer your question? – Aristotelis V Sep 15 '22 at 11:53
  • The answer to all of your questions is it is an implementation detail and usually the reason capacity is not the same as size is to improve performance. – drescherjm Sep 15 '22 at 12:54
  • ***However, if I pop back some elements, the size is reduced but the capacity remains the same. Does this always happen?*** No, there will likely be some threshold that will cause the capacity to reduce. You can test an implementation yourself by creating a vector with for example a GB of data then remove data in a loop printing the size and capacity on each pop_back() or maybe only print when the capacity changes. This is a program that is most likely less than 20 lines of code to write. – drescherjm Sep 15 '22 at 12:54
  • Here is an example that should help clear up some of these questions: [https://ideone.com/pf0eDE](https://ideone.com/pf0eDE) – drescherjm Sep 15 '22 at 13:07

0 Answers0