Module 8 · The Standard Template Library — topic 2 of 7
Vectors in Depth
std::vector internals: size vs capacity, growth and reallocation, emplace_back, erase-remove, sorting and searching, and iterator invalidation.
Learning objectives
- Explain size, capacity and reallocation
- Insert and erase elements efficiently
- Avoid iterator invalidation bugs
Definition
std::vector<T> is a sequence container storing elements contiguously in a dynamically allocated array that grows geometrically, providing O(1) random access and amortised O(1) insertion at the end.Introduction
A vector keeps a block of memory larger than it needs. When the block fills, it allocates a bigger one (typically 1.5× or 2×), moves the elements and frees the old block. That is why push_back is fast on average but can occasionally invalidate pointers to elements.
Because elements are contiguous, a vector can be passed to C functions expecting a pointer and length, and iterating it is extremely cache-friendly. These two properties explain why experienced C++ programmers reach for vector first and only switch containers after measuring.
Why it matters
Vector is the most used container; knowing its costs makes programs fast.
Erasing while iterating is a common source of crashes.
Detailed explanation
size() is the number of elements; capacity() is how many fit before reallocation. reserve(n) pre-allocates; shrink_to_fit() requests releasing unused capacity.
emplace_back(args...) constructs the element in place instead of constructing then copying/moving.
Inserting or erasing in the middle shifts later elements: O(n).
Erase-remove idiom: v.erase(std::remove_if(v.begin(), v.end(), pred), v.end()); removes all matching elements in one pass. C++20: std::erase_if(v, pred).
Reallocation invalidates all iterators, pointers and references; erasing invalidates those at or after the erase point.
Syntax
- Reserve when the final size is known.
clear()sets size to 0 but usually keeps capacity.data()gives a pointer to the contiguous storage.
Code examples
Size and capacity
6 1 0 1
emplace_back
penx3 bookx1
More examples
Erase-remove, sort and binary search
55 64 77 91 1 77 at index 2
Step-by-step explanation
remove_ifmoves the kept elements forward and returns the new logical end.erasethen deletes the leftover tail in one call.- Binary search requires sorted data.
lower_boundreturns the first element not less than 70.
Expected output
Running “Erase-remove, sort and binary search” prints exactly:
Practical applications
- Particle systems store particles in vectors and erase dead ones each frame.
- Leaderboards are sorted vectors.
- Buffers passed to C APIs use
v.data().
Best practices
- Use reserve for known sizes.
- Use erase-remove (or std::erase_if) to delete by condition.
- Re-acquire iterators after modifying the vector.
Common mistakes
Erasing inside a range-for
Avoid
Prefer
erase invalidates it; incrementing it afterwards is undefined behaviour.
Keeping a pointer across push_back
Avoid
Prefer
If push_back reallocates, first dangles.
Important notes
- Growth factor is implementation-defined (libstdc++ doubles, MSVC grows by 1.5×).
std::vector<bool>stores bits, so&v[0]is not abool*.
Key takeaways
- capacity ≥ size; reallocation invalidates everything.
- emplace_back constructs in place.
- Erase-remove deletes by condition efficiently.
Try it yourself
- 1Remove duplicates from a vector using sort + unique + erase.
- 2Print capacity after each push_back for 20 pushes and describe the growth pattern on your compiler.
Finished reading? Mark it complete to update your dashboard.
Suggested practice
6 questions test this exact topic. Answers and explanations are revealed after you submit.
- BeginnerWhat is the difference between size() and capacity() of a vector?
- BeginnerWhat does `emplace_back` do differently from `push_back`?
- ModerateWhat is printed?