std::vector
A resizable array that keeps its elements in one contiguous block of heap memory. It owns that block, grows it on demand, and frees it in its destructor, which makes it the default container for a sequence of values.
Detailed Explanation
Reach for std::vector unless you have measured a reason not to. It stores elements back to back in a single heap allocation, so element i sits exactly i * sizeof(T) bytes after the first. That contiguous layout is the whole performance story. A CPU fetches memory in 64-byte cache lines, so walking a vector pulls the next several elements into cache for free, and the hardware prefetcher can see the access pattern coming.
Two numbers describe a vector. size() is how many elements exist. capacity() is how many the current allocation could hold before it must be replaced. Capacity is always at least size, usually more.
When a push_back would take size past capacity, the vector allocates a larger block, moves or copies every existing element across, destroys the originals, and frees the old block. That one call is O(n). It is rare, because implementations multiply capacity by a constant growth factor — 2 on libstdc++ and MSVC, 1.5 on libc++ — instead of adding a fixed number of slots. With doubling, n pushes trigger about log n reallocations that move 1 + 2 + 4 + … + n ≈ 2n elements in total, so the cost averaged over all the pushes is constant. That is what amortised O(1) means: an individual push_back can be slow, but a run of them is linear overall. Had growth added a fixed 10 slots each time, the same run would be O(n²).
reserve(n) does that reallocation once, up front, when you know roughly how many elements are coming. It changes capacity, never size. shrink_to_fit() asks the vector to release unused capacity; it is a non-binding request and may reallocate, so treat it as a hint, not a guarantee.
emplace_back(args...) constructs the element directly in the vector's storage from constructor arguments. push_back(x) takes a finished object and copies or moves it. v.emplace_back(10, 'x') builds one std::string; v.push_back(std::string(10, 'x')) builds a temporary and then moves it. Prefer emplace_back when you are constructing from parts.
Complexity: indexing, front, back, data, pop_back are O(1); push_back is amortised O(1); insert and erase at position i are O(n − i) because everything after shifts; searching is O(n). Middle insertion is technically worse than std::list's O(1), yet vector usually still wins at small and medium sizes, because the shift is one linear pass over contiguous memory while a list pays a pointer chase and an allocation per node.
Invalidation is exam material, and iterators, pointers, and references do not always share a fate:
| Operation | Iterators | Pointers and references |
|---|---|---|
Reallocation (push_back past capacity, reserve, shrink_to_fit) | all invalid | all invalid |
push_back with spare capacity | only end() invalid | all stay valid |
insert at position p (no reallocation) | invalid from p onward | invalid from p onward |
erase at position p | invalid from p onward | invalid from p onward |
pop_back | removed element and end() | removed element only |
clear | all invalid | all invalid |
One special case: std::vector<bool> is not a real container. It is a space optimisation that packs eight values per byte, so operator[] returns a proxy object rather than a bool&, and &v[0] is not a bool*. Use std::vector<char>, std::deque<bool>, or std::bitset when you want ordinary behaviour.
Code Examples
#include <iostream>
#include <string>
#include <vector>
int main() {
std::vector<std::string> lines;
lines.reserve(3); // one allocation instead of several
std::cout << lines.size() << ' ' << lines.capacity() << '\n'; // prints: 0 3
lines.push_back("already built"); // copies the temporary in
lines.emplace_back(5, '-'); // constructs "-----" in place, no temporary
std::cout << lines.size() << ' ' << lines.capacity() << '\n'; // prints: 2 3
std::cout << lines.back() << '\n'; // prints: -----
}#include <vector>
void invalidation() {
std::vector<int> v{1, 2, 3};
int& first = v[0];
v.push_back(4); // capacity was 3, so this reallocates
// first now refers to freed memory: reading it is undefined behavior.
// Erasing inside a loop: erase returns the iterator to the next element.
std::vector<int> nums{1, 2, 3, 4, 5, 6};
for (auto it = nums.begin(); it != nums.end(); ) {
if (*it % 2 == 0) it = nums.erase(it); // reseat, do not ++it
else ++it;
}
// nums is now {1, 3, 5}
}Common Gotchas
A saved reference does not survive a reallocation
holding `int& x = v[0];` or `int* p = v.data();` across any growing `push_back` leaves you pointing at freed memory. Reading it is undefined behavior, which means the compiler may do anything at all, including appearing to work in a debug build. Store an index instead, or `reserve` before you take the reference.
`erase` inside a loop needs the returned iterator
`v.erase(it); ++it;` increments an invalidated iterator. Use `it = v.erase(it)` and only `++it` on the branch where you did not erase. For bulk removal prefer `std::erase_if(v, pred)` (C++20), which replaces the old erase-remove idiom `v.erase(std::remove_if(...), v.end())`.
`resize` and `reserve` are not the same thing
`reserve(100)` leaves `size()` at 0 and gives you room; `resize(100)` creates 100 value-initialised elements. Calling `reserve` then `v[0] = x` is out-of-bounds access on an empty vector.