Opening the reading…
Opening the reading…
PROGRAMMING FUNDAMENTALS › C++ FUNDAMENTALS
Suppose values contains [4, 2]. Its size is 2, so it has two elements: values[0] is 4 and values[1] is 2. Its capacity is 4, so the vector has storage ready for four elements, but the extra storage does not count as elements. Capacity answers how many elements can fit before new storage is needed. Size answers how many elements currently exist.
The only valid indices are 0 through size - 1. Therefore values[2] and values[3] are outside the vector's element range. They are not empty elements waiting to be filled by indexing. They are spare storage managed by the vector, and using them as if they were elements produces invalid access even though the storage has already been allocated.
values contains [4, 2], has size 2, and has capacity 4. Which indices are valid for accessing vector elements?
Checkpoints are not graded. They are here so you catch yourself before the quiz does — stuck, ask the tutor on the right.
Starting with values = [4, 2], size 2, and capacity 4, push_back(7) adds 7 after the existing elements. The vector becomes [4, 2, 7]. Its size increases to 3, while its capacity stays 4 because one of the reserved slots was available.
A second push_back(1) uses the last spare slot. The vector becomes [4, 2, 7, 1], its size becomes 4, and its capacity remains 4. The newly valid indices are now 2 and 3, because adding elements changed the size. The storage did not become valid merely because it existed; each push_back created one element in that storage.
Now values is [4, 2, 7, 1], with size 4 and capacity 4. There is no spare capacity for push_back(9). The vector must obtain different backing storage that can hold at least five elements, then move or copy the old elements before placing 9 after them.
In the observed trace, the new storage has capacity 8. The resulting vector is [4, 2, 7, 1, 9], with size 5. The first five slots contain elements, while the remaining three slots are spare storage. The values and their order survive the replacement, but the backing storage itself may be somewhere else.
What is the size immediately after push_back(9) changes [4, 2, 7, 1] into [4, 2, 7, 1, 9]?
Checkpoints are not graded. They are here so you catch yourself before the quiz does — stuck, ask the tutor on the right.
The trace observes capacity changing from 4 to 8 when 9 is appended. That is a common growth pattern, but C++ does not promise that exact result. The guarantee is that the new capacity is enough for the five elements. An implementation could choose another capacity, such as 5 or a larger value.
You may inspect capacity when you need to understand the current storage state, and you may rely on size to determine the element range. You must not write code that assumes every full vector doubles its capacity. Such code can fail when the same program uses a different standard library or implementation.