Capacity of a std::vector determines how many elements it is capable to store (or have storage to store). For instance, if a vector has memory to store 6 elements then this will be called its capacity.

We can get capacity of a vector using capacity() member function as shown below:

std::vector items{1, 2, 3, 4, 5};
std::cout < items.capacity(); // 5

How is it different from length(size)?

Length of a vector determines how many elements a vector currently holds. For instance, a vector has capacity for 6 elements but it is currently holding only 3 elements.

For example,

items.resize(3);
std::cout << items.size(); // 3
std::cout << items.capacity(); // 5

We have resized vector to store 3 elements (at least), the length is 3 but the capacity is 5. Why? Because resize did not free the memory, vector still has memory for 2 more elements. I have discussed resize in this note.

Vector indexing is based on the length, not capacity

As we saw in above section, the length is 3 and capacity is 5. It means that vector has 3 elements but store for 5 elements. So, there are only 3 valid indices for 3 elements (0, 1, 2), not 5 (0, 1, 2, 3, 4).

This means that indexing is based on the length, not the capacity of the vector.

References

  1. https://www.learncpp.com/cpp-tutorial/stdvector-resizing-and-capacity/