std::vector allocates a memory on heap and store all its elements in contiguous memory location.

But what if memory it allocated initially is completely filled?
For example, let’s create a vector of ints i.e. std::vector<int> . Now suppose it’s initial capacity is to store 10 elements, but in our application we want to store 15 elements in it. Then what will happen when we will insert 11th element?

When std::vector’s internal memory completely finishes then it increases the size of its memory. To do that it performs following steps,

1.) It will allocate a bigger chunk of memory on heap i.e. almost double the size of previously allocated.
2.) Then it copies all the elements from old memory location to new one. Yes it copies them, so in case our elements are user defined objects then their copy constructor will be called. Which makes this step quite heavy in terms of speed.
3.) Then after successful copying it deletes the old memory.

You can check the current capacity of vector i.e. how much elements it can store in current allocated memory using capacity() member function.
To check the count of currently stored elements in std::vector one can use size() member function.

Check out this example,


Python Recommendations:

C++ & C++11 Recommendations:

If you didn't find what you were looking, then do suggest us in the comments below. We will be more than happy to add that.

Subscribe with us to join 1500+ Python & C++ developers, to get more Tips &  Tutorials like this.