Understanding capacity versus size
As you venture deeper into the art of C++ programming with std::vector
, it becomes crucial to grasp the distinctions between a vector’s size and capacity. While closely related, these terms serve different roles in managing and optimizing dynamic arrays, and understanding them will dramatically enhance both the efficiency and clarity of your code.
Revisiting the basics
Recall from the previous chapter that the size of a vector denotes the number of elements it currently holds. When you add or remove elements, this size adjusts accordingly. So, if you have a vector containing five integers, its size is 5
. Remove an integer, and the size becomes 4
.
But herein lies a compelling facet of std::vector
: while its size changes based on its elements, the memory it allocates doesn’t always follow suit immediately. To understand this thoroughly, we need to explore the concept of capacity. Let us do that in the next section.