Difference Between Size and Capacity of a Vector in C++ STL
In this article, we are going to study the difference between the size and capacity of a vector in C++ STL. The size of the vector is defined as the total number of elements present in the vector. Vector is a dynamic array so it changes with the user input, unlike the static arrays which we define with the subscript operators “” which remain constant throughout the program and throw errors if we try to input more than the array size. Vectors can change their size and capacity according to the user input. Vectors are known as dynamic arrays with the ability to resize themselves automatically when an element is inserted or deleted.
In the case of vectors:
vector<int> v; v.size() <-- For size of the vector. v.capacity() <-- For capacity of the vector.
The above code and its output clearly show that the size of the vector represents the total number of elements that we store in the vector. But capacity acts a bit differently compared to size.
You can easily observe the difference between the size and capacity of the vectors. Whenever the size of the vector becomes equal to the capacity, the vector will automatically increase its capacity and make it twice as large.
There is a difference between size and capacity. The capacity of a vector is the total number of elements it can hold. The total amount of storage is what capacity is, but how much content (elements) are there inside the vector is what the size of a vector represents.
The reason for this difference is the internal implementation of the vector. Unlike static arrays which are rigid in their capacity, vectors are flexible in their capacity, because vectors are dynamic in nature.
So, the size of the array is 9 because there are only 9 elements present in the vector although its capacity is 16, which means you are allowed to store up to 16 elements, and once the number of elements becomes equal to capacity it will modify itself and again increase its capacity.
Please Login to comment...