Size vs capacity in a vector

Size vs capacity in a vector

Ever wondered what is the difference between the methods size and capacity in vector. Wonder no more, I've got you covered

#include <iostream>
#include <vector>
using namespace std;

int main() 
{
    vector<int> box(4,0);  //L1
    cout<<"Size: "<<box.size()<<" Capacity: "<<box.capacity()<<endl; 
    //Size: 4 Capacity: 4

    box.push_back(1);  //L2
    cout<<"Size: "<<box.size()<<" Capacity: "<<box.capacity(); 
    // Size: 5 Capacity: 8

    return 0;
}

In L1, a vector of int is initialized with 4 elements
image.png

In L2, one more element is inserted, the capacity becomes doubled,

image.png

What kind of sorcery is this ? Why does this happen. I know, it's okay to be confused.

image.png

We're going to uncover the mystery step by step

The main selling point of vector over a traditional array is the ability to allocate memory dynamically at runtime. Size and capacity of a vector are tied closely to this allocation

Vector grows memory in exponential fashion, For example, let us consider an example, where elements are pushed back into vector in a loop, Consider the following example, i know it's boring, where a integer with value 10 is pushed back into a vector for 50 times

for( int index = 0; index < 50; index++)
    box.push_back(10);

In a vector, size has to be always lesser than or equal to capacity, when the number of elements in a vector is about to exceed capacity, then capacity is doubled. This is how a vector grows in size exponentially as more and more elements get into it

Let us have a look at how size and capacity varies, as we run through this loop,
After pushing first element,
size = 1 capacity = 1

Now we don't have anymore space left in the vector, on the next attempt to push an element into vector, allocate more memory, capacity will be doubled, copy existing elements to newly allocated block and insert the new element,
size = 2 capacity = 2

Another element enters the vector, capacity gets doubled again,
size = 3 capacity = 4

But notice how a new element can be inserted now without a memory allocation
size = 4 capacity = 4

Point to note is, new heap allocation is not done until capacity is breached.
When available capacity is utilized completely, capacity is doubled

Did you find this article valuable?

Support cppnuggets by becoming a sponsor. Any amount is appreciated!