C++ Vector Tutorial: Contiguous Storage and Element Invalidation
std::vector stores a sequence of values contiguously under its container contract. Size counts live elements, while capacity describes available storage before applicable growth requires reallocation. Operations can relocate or shift elements, so retaining references into a vector requires attention to the specific change being performed.
Here's a popular C++ Vectors video — watch it, then summarize it with one click. Or paste any other YouTube link below.
— or paste your own YouTube link —
Want to keep the key points from a YouTube video? Paste the link below to turn it into structured notes.
Why Use C++ Vector Tutorial: Contiguous Storage and Element Invalidation
- Distinguish size from capacity
- Understand contiguous element access
- Relate growth to reallocation
- Track references after insertion or erasure
- Use reservation without assuming elements were created
Frequently Asked Questions
Does reserving capacity create that many elements?
Reservation manages storage capacity under the vector's rules rather than increasing its size to the requested count. Access still needs a live element within the current size, not merely reserved space.
Why can growth invalidate element references?
Growth can require a new storage allocation and relocation of existing elements. References and iterators associated with earlier storage then need the operation's invalidation rules rather than remaining valid automatically.
How does erasing an element affect later positions?
Erasure changes the sequence and can shift later elements into earlier positions. Index and iterator interpretation therefore needs the resulting sequence rather than assuming every remaining element keeps its former location.
Is unchecked indexing a bounds guarantee?
Unchecked element access expects the caller to supply a valid position under its contract. A numeric index being representable does not establish that it identifies an existing element within the vector.
When is reserving space useful?
Reservation can reduce reallocations when an expected element count is known. Its benefit depends on insertion patterns and memory requirements rather than every larger reservation automatically improving a program.