Explain it simply
Vectors in plain language
A plain array has a size fixed when you write the code. Real lists are not like that: a to-do app cannot know how many tasks the user will add, and a file reader cannot know how many lines are coming. std::vector is a list that grows as you add items while keeping them side by side in memory, so reading item number 5 is as fast as with a plain array.
Picture a row of numbered lockers. When every locker is full, the vector rents a longer row, moves all the contents across and hands the old row back. Most of the important rules in this lesson come from that move.
Problem → Why → Solution
The problem: the task that vanished
You keep a reference to the first task so you can get back to the one you are working on. Then you add a batch of new tasks and print current. Sometimes the right text appears, sometimes garbage characters, sometimes the program crashes. The code compiles without a single warning.
#include <iostream>
#include <string>
#include <vector>
int main() {
std::vector<std::string> tasks{"Write report"};
std::string& current = tasks[0]; // reference into the vector
for (int i = 0; i < 100; ++i) {
tasks.push_back("Task " + std::to_string(i)); // may move every element
}
std::cout << "Working on: " << current << '\n'; // undefined behaviour
}Why current broke
A vector keeps its elements in one contiguous block of memory. When push_back needs more room than the block has, the vector allocates a bigger block, moves every element over and frees the old one. current still points into the freed block. If the old bytes happen to survive, the program looks fine, but it is undefined behaviour, and it is the most common vector bug there is.
Core concept: size, capacity and one contiguous block
An std::vector<T> owns one block on the heap and tracks three things: where the data starts, how many elements are in use (size) and how many fit before it must reallocate (capacity). A vector is a value type: copying it copies every element, and at the end of its scope it frees its own memory, so you never write delete (RAII).
push_back(value) copies or moves a value onto the end, while emplace_back(args...) constructs the element right there. When the block is full, capacity grows by a factor, so most push_backs are cheap (amortized constant time). The factor is implementation-defined and differs between standard libraries, so never rely on a number. If you know how many elements are coming, reserve(n) allocates once.
When reading, v[i] checks nothing, and an index out of range is undefined behaviour. v.at(i) checks and throws std::out_of_range. front() and back() on an empty vector are undefined too. size() returns std::size_t, which is unsigned, so on an empty vector v.size() - 1 is not -1 but a huge number. Pass a vector to functions by const& to read it and by & to change it; by value copies every element.
| Operation | What it invalidates |
|---|---|
| push_back / emplace_back | everything if it reallocates, otherwise only end() |
| insert in the middle | the insertion point and after (all on reallocation) |
| erase(it) | the erased element and everything after it |
| reserve(n) above capacity, clear() | everything |
| reading with [], at() or range-for | nothing |
Removing is the other expensive direction: erase shifts every later element one place left, so it costs time in proportion to what follows. In C++20, std::erase(v, value) and std::erase_if(v, predicate) remove every match in a single pass and return how many they removed.
- Elements sit in one contiguous block
- size: slots used; capacity: all slots
- Full? Allocate bigger, move everything
- Old references now point at nothing
If you must remember an element across push_backs, remember its index, not a reference or an iterator.
General pattern
std::vector<Type> items; // empty
std::vector<Type> items{a, b, c}; // with initial elements
items.push_back(value); // add to the end
items.reserve(n); // room for n, size unchanged
items[i]; items.at(i); // unchecked / checked access
items.size(); items.empty();
for (const Type& item : items) { /* read */ }
std::erase_if(items, predicate); // C++20: remove every matchName the element type in angle brackets, add to the end, read by index and loop by const&. Call reserve before the first insertion when you know how many elements are coming.
Worked example: a task list
The program adds three tasks, prints them, changes one and removes the first. Watch the type of the loop variable: const std::string& means no string is copied on any pass. The last two lines show that after erase, the remaining elements have shifted left.
#include <iostream>
#include <string>
#include <vector>
int main() {
std::vector<std::string> tasks; // starts empty: size() == 0
tasks.push_back("Learn variables");
tasks.push_back("Practice loops");
tasks.emplace_back("Build a mini project"); // constructs the string in place
for (const std::string& task : tasks) { // const& reads without copying
std::cout << "- " << task << '\n';
}
tasks[1] = "Practice for and while loops"; // [] does no bounds check
std::cout << "second: " << tasks.at(1) << '\n'; // at() checks the index
tasks.erase(tasks.begin()); // later elements shift left
std::cout << "first now: " << tasks.front() << '\n';
std::cout << "Total tasks: " << tasks.size() << '\n';
}Code breakdown
- Start empty
std::vector<std::string> tasks;A vector with no elements; size() is 0. The element type is std::string, so trying to add an int is a compile error.
- Construct in place
tasks.emplace_back("Build a mini project");emplace_back passes its argument straight to std::string's constructor, building the string inside the vector. For a simple case like this the result is the same as push_back.
- Read without copying
for (const std::string& task : tasks) {const& looks at the element inside the vector and forbids changing it. Writing std::string task instead would copy on every pass, and changing task would not change the vector.
- Unchecked write, checked read
tasks[1] = "Practice for and while loops";Writing with [] is fine because index 1 is known to exist. The next line uses at(1), which would throw std::out_of_range instead of causing undefined behaviour if the index were missing.
- Erase shifts the rest
tasks.erase(tasks.begin());begin() points at the first element. After erasing it, the rest shift one place left, so the edited task becomes front() and the size is 2.
- Learn variables
- Practice loops
- Build a mini project
second: Practice for and while loops
first now: Practice for and while loops
Total tasks: 2Watching capacity and reserve
You can tell whether a push_back reallocated by checking if capacity() changed. The program below pushes a thousand numbers into two vectors: one grows on its own, the other starts with reserve(1000). The exact number of reallocations depends on the library, so the program prints only whether it happened, not how often.
#include <iostream>
#include <vector>
int countReallocations(std::vector<int>& v, int items) {
int moves = 0;
std::size_t lastCapacity = v.capacity();
for (int i = 0; i < items; ++i) {
v.push_back(i);
if (v.capacity() != lastCapacity) { // capacity changed = new block
++moves;
lastCapacity = v.capacity();
}
}
return moves;
}
int main() {
std::vector<int> grown;
std::vector<int> reserved;
reserved.reserve(1000); // one allocation up front
std::cout << std::boolalpha;
std::cout << "grown reallocated: " << (countReallocations(grown, 1000) > 0) << '\n';
std::cout << "reserved reallocated: " << countReallocations(reserved, 1000)
<< " times\n";
std::cout << "capacity >= size: " << (grown.capacity() >= grown.size()) << '\n';
}The output is grown reallocated: true, reserved reallocated: 0 times and capacity >= size: true. The standard guarantees that after reserve(n), insertions do not reallocate until the size would exceed n, so the second line says 0 on every compiler. About the exact capacity, the only portable fact is that it is never smaller than the size.
Removing safely and checked access
std::erase_if takes the vector and a function that answers "should this element go?". Here it is a plain named function; lesson 28 shows how a lambda replaces it. The program also shows at() turning a bad index into an exception you can catch, instead of undefined behaviour.
#include <iostream>
#include <stdexcept>
#include <vector>
bool isFailing(int score) { return score < 40; }
int main() {
std::vector<int> scores{72, 35, 90, 18, 64};
auto removed = std::erase_if(scores, isFailing); // C++20, <vector>
std::cout << "removed " << removed << ", left:";
for (int s : scores) std::cout << ' ' << s;
std::cout << '\n';
try {
int value = scores.at(10); // index 10 does not exist
std::cout << value << '\n';
} catch (const std::out_of_range&) {
std::cout << "at(10) threw std::out_of_range\n";
}
}It prints "removed 2, left: 72 90 64" and then "at(10) threw std::out_of_range". Notice that the surviving elements keep their original order.
In real projects
Vectors in real projects
The C++ Core Guidelines recommend std::vector as the default container unless you have a specific reason to pick another. Because the elements sit next to each other, it works very well with the CPU cache and is often faster than a list or a map in practice:
- Rows from a file or an API response are loaded into std::vector<Record>, then sorted, filtered and reported. When a header announces the row count, the code starts with reserve.
- Games keep their entities in vectors and loop over them every frame. They store indices or ids between frames rather than pointers, precisely because of the invalidation rules in this lesson.
- Network and file buffers use std::vector<char> or std::vector<std::byte>, and data() hands a contiguous pointer to C APIs that expect one.
Common mistakes
Common mistakes with vectors
Holding a reference or iterator across push_back
This is the bug from the problem section. Reallocation frees the old block and everything pointing into it dangles. Store an index, take the reference again after the change, or reserve first when you know the final size.
Erasing inside a range-for loop
A range-for loop holds a hidden iterator. Calling erase inside the loop invalidates it, and you get skipped elements or a crash. Use std::erase_if, or an explicit iterator loop that continues from the iterator erase returns.
Tripping over the unsigned size()
for (std::size_t i = 0; i <= v.size(); ++i) reads v[v.size()], which is undefined behaviour; use <. On an empty vector, v.size() - 1 becomes 18446744073709551615 on a 64-bit system, so check empty() before doing subtraction.
Passing vectors by value
void print(std::vector<std::string> list) copies every string on each call, and changes made inside never reach the caller's vector. Use const& to read and & to modify.
Mini challenge
Mini challenge: a playlist without duplicates
Write three functions for a playlist stored in std::vector<std::string>. addSong refuses a title that is already there and returns false; removeSong removes every copy of a title and returns how many it removed; printPlaylist prints a numbered list.
- addSong takes the vector by & and uses std::find to search it
- removeSong uses C++20 std::erase and returns the number removed
- printPlaylist takes the vector by const& and numbers the songs from 1
- Try adding one title twice and print the result
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
// Adds title unless it is already in the playlist; returns whether it was added.
bool addSong(std::vector<std::string>& playlist, const std::string& title) {
// TODO: search with std::find; push_back only when the title is missing
return false;
}
// Removes every copy of title; returns how many were removed.
std::size_t removeSong(std::vector<std::string>& playlist, const std::string& title) {
// TODO: one call to std::erase does the work
return 0;
}
void printPlaylist(const std::vector<std::string>& playlist) {
// TODO: print "1. title", "2. title", ... with an index loop
}
int main() {
std::vector<std::string> playlist;
// TODO: add "Morning Run", "Focus Beats", "Morning Run" again, "Night Drive"
// TODO: print, remove "Focus Beats", print again and show the size
}Expected: The second "Morning Run" returns false, so the playlist holds three songs. Removing "Focus Beats" reports removed: 1, removing a missing title reports 0, and the final size is 2.
Show hint
std::find(playlist.begin(), playlist.end(), title) returns playlist.end() when nothing matches. In the print loop, run a std::size_t index from 0 up to but not including size(), and show i + 1.
Show solution
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
bool addSong(std::vector<std::string>& playlist, const std::string& title) {
if (std::find(playlist.begin(), playlist.end(), title) != playlist.end()) {
return false; // already in the list
}
playlist.push_back(title);
return true;
}
std::size_t removeSong(std::vector<std::string>& playlist, const std::string& title) {
return std::erase(playlist, title); // C++20: returns how many were removed
}
void printPlaylist(const std::vector<std::string>& playlist) {
for (std::size_t i = 0; i < playlist.size(); ++i) {
std::cout << i + 1 << ". " << playlist[i] << '\n';
}
}
int main() {
std::vector<std::string> playlist;
std::cout << std::boolalpha;
std::cout << "add Morning Run: " << addSong(playlist, "Morning Run") << '\n';
std::cout << "add Focus Beats: " << addSong(playlist, "Focus Beats") << '\n';
std::cout << "add Morning Run again: " << addSong(playlist, "Morning Run") << '\n';
addSong(playlist, "Night Drive");
printPlaylist(playlist);
std::cout << "removed: " << removeSong(playlist, "Focus Beats") << '\n';
std::cout << "removed missing: " << removeSong(playlist, "Unknown") << '\n';
printPlaylist(playlist);
std::cout << "size: " << playlist.size() << '\n';
}Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- std::vector stores elements in one contiguous block, grows on demand and frees its memory at the end of its scope.
- [] is unchecked, at() checks and throws std::out_of_range, and front() or back() on an empty vector is undefined.
- size counts elements in use, capacity counts room; the growth factor is implementation-defined and reserve avoids reallocations.
- Reallocation, insert and erase invalidate iterators, pointers and references, so store indices instead.
- C++20 std::erase and std::erase_if remove every match without the dangers of erasing inside a loop.
The Current ISO C++ Standard (C++23) — Standard C++ Foundation