C++ What is the difference between capacity and size of the vector?

www.igif‮t‬idea.com

In C++, a vector has two important attributes: size and capacity.

The size of a vector is the number of elements it currently holds. You can get the size of a vector using the size() method. For example:

std::vector<int> v {1, 2, 3, 4, 5};
std::cout << "Size of the vector is: " << v.size() << std::endl;

Output:

Size of the vector is: 5

The capacity of a vector is the amount of memory it has allocated for storing elements. It's the maximum number of elements a vector can hold without needing to allocate more memory. You can get the capacity of a vector using the capacity() method. For example:

std::vector<int> v {1, 2, 3, 4, 5};
std::cout << "Capacity of the vector is: " << v.capacity() << std::endl;

Output:

Capacity of the vector is: 5

When you add elements to a vector, its size increases. If the size of the vector exceeds its capacity, the vector needs to allocate more memory to accommodate the new elements. This process of allocating new memory is called reallocation. Reallocation can be an expensive operation, as it involves copying all the existing elements to the new memory location.

It's important to note that the capacity of a vector is always greater than or equal to its size. In other words, a vector can hold more elements than the number of elements it currently holds. The reserve() method can be used to preallocate memory for a vector to avoid reallocations. The resize() method can be used to change the size of a vector, while reserve() only changes its capacity.