Your country

Tools that support it use your country for local currency, number formats, units and paper size. Your choice is saved only in this browser.

Type a name or a two-letter code. Use the up and down arrow keys to move through the countries, Enter to choose one and Escape to close.

C++  Module 5 – Arrays, vectors and aggregate types

std::vector: the container to reach for first

Create, grow and loop over a std::vector, watch size and capacity change with two compilers, and catch out-of-range reads with at() and hardened builds.

  • Beginner
  • 20 minutes
  • Examples run with Clang 21.0.0, GCC 16.2.0 and Python 3.14.8
  • By MySmartCoPilot
Free lesson, Pro answers: 20 minutes
Free: the whole lesson. With a pass: the model answers to its 2 interview questions.

What you will learn

  • Create, grow and iterate a std::vector
  • Predict a vector's size, capacity and reallocations as it grows
  • Use indexes instead of references across calls that can reallocate
  • Choose between operator[], at() and hardened builds for bounds safety
  • Remove elements with std::erase and std::erase_if
What you’ll learn

What you will learn

  • Create, grow and iterate a std::vector
  • Predict a vector's size, capacity and reallocations as it grows
  • Use indexes instead of references across calls that can reallocate
  • Choose between operator[], at() and hardened builds for bounds safety
  • Remove elements with std::erase and std::erase_if
On this page

Adding 1,000 values to an empty std::vector<int> with push_back took 11 allocations and moved 1,023 elements, in both libc++ and libstdc++; calling reserve(1000) first cut that to one allocation. std::vector<T> is C++’s resizable array. It keeps any number of values of one type T side by side in a single block of memory, adds new values at the end quickly, gives you any element by its position in one step, and frees its memory by itself when it goes out of scope.

Below, vectors are built and read first. Then the lesson looks inside: how a vector’s size differs from its capacity: The number of elements a vector's buffer has room for, never less than its size. A push_back into a full buffer reallocates; reserve(n) raises the capacity to at least n without adding elements, and clear() leaves it as it was., what the two common standard libraries do when a vector grows, why growing leaves old pointers and references dangling, and what happens when an index is out of range, which depends on the compiler, the optimisation level and the library.

A vector keeps its elements in order and adds at the end

Because the elements sit next to each other, a vector is also the fastest standard container to loop over. That is why the C++ Core Guidelines tell you to use vector by default and to choose another container only when you have a reason to. The examples use two compilers: Apple clang with its standard library, libc++, and GCC 16 with libstdc++.

basics.cpp C++ · basics.cpp
// Creating, growing and reading a std::vector.
#include <cstddef>
#include <print>
#include <string>
#include <vector>

int main() {
    std::vector<int> marks{71, 64, 88};      // three elements, from a braced list
    marks.push_back(92);                     // add at the end
    marks.push_back(57);
    std::println("marks: {}", marks);        // C++23 prints a whole range
    std::println("size {}, first {}, last {}", marks.size(), marks.front(), marks.back());

    int total = 0;
    for (int m : marks) total += m;          // range-for visits every element in order
    std::println("total {}", total);

    for (std::size_t i = 0; i < marks.size(); ++i) {   // an index loop when the position matters
        if (marks[i] < 60) std::println("marks[{}] = {} needs a second attempt", i, marks[i]);
    }

    std::vector<int> five_zeros(5);          // (count): five value-initialised ints
    std::vector<int> five_sevens(5, 7);      // (count, value)
    std::vector<int> just_five{5};           // braces: one element, the number 5
    std::println("{} {} {}", five_zeros, five_sevens, just_five);

    std::vector<std::string> names;
    names.emplace_back(3, 'a');              // builds std::string(3, 'a') in place: "aaa"
    names.push_back("Ravi");                 // builds a temporary string, then moves it in
    std::println("{}", names);
}
Built and run with both compilers Python · basics_session.py
from session import run

# basics.cpp built and run with Apple clang and its library, libc++, then with GCC 16 and libstdc++.
run("""
clang++ -std=c++23 -Wall -Wextra basics.cpp -o basics
./basics
g++-16 -std=c++23 -Wall -Wextra basics.cpp -o basics-gcc
./basics-gcc
""")

Output

$ clang++ -std=c++23 -Wall -Wextra basics.cpp -o basics
$ ./basics
marks: [71, 64, 88, 92, 57]
size 5, first 71, last 57
total 372
marks[4] = 57 needs a second attempt
[0, 0, 0, 0, 0] [7, 7, 7, 7, 7] [5]
["aaa", "Ravi"]
$ g++-16 -std=c++23 -Wall -Wextra basics.cpp -o basics-gcc
$ ./basics-gcc
marks: [71, 64, 88, 92, 57]
size 5, first 71, last 57
total 372
marks[4] = 57 needs a second attempt
[0, 0, 0, 0, 0] [7, 7, 7, 7, 7] [5]
["aaa", "Ravi"]

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 basics_session.py

The two programs print the same lines. What each part does:

  • std::vector<int> marks{71, 64, 88}; creates a vector of three int elements from a braced list. The type in the angle brackets is the element type, and the header is <vector>.
  • push_back(x) adds an element at the end. size() says how many elements there are, front() and back() give the first and the last, and marks[i] gives the element at index i, which runs from 0 to size() - 1.
  • std::println("{}", marks) prints the whole vector in square brackets. Printing ranges this way is new in C++23; older code loops and prints each element.
  • The range-based for: A loop of the form for (declaration : range) that runs its body once for each element of an array, a container or another range, in order, with no index to manage. auto copies each element; auto& refers to it. More in “C++ loops: while, do-while, for and range-for” visits every element in order. For large elements such as strings, write for (const std::string& name : names) so that each element is read in place instead of copied.
  • When the position matters, loop over the indexes with std::size_t, the unsigned type that size() returns. With an int index, i < marks.size() compares a signed number with an unsigned one, and both compilers warn about it under -Wall -Wextra.

Step through the lines that use marks, one at a time, and watch what the vector holds after each:

Interactive · stage by stage The vector marks through the first lines of basics.cpp Step through the program. Each stage is one line that uses marks; its sub-label shows what marks holds, or what the line read.
The vector marks through the first lines of basics.cpp, step 6 of 6. Showing marks{71, 64, 88} (71 64 88), push_back(92) (71 64 88 92), push_back(57) (71 64 88 92 57), size(), front(), back() (size 5, front 71, back 57), for (int m : marks) (total 372), marks[i], i < size() (marks[4] = 57 is below 60). In focus: marks[i], i < size().marks{71, 64, 88}71 64 88push_back(92)71 64 88 92push_back(57)71 64 88 92 57size(), front(), back()size 5, front 71, back 57for (int m : marks)total 372marks[i], i < size()marks[4] = 57 is below 60

The drawing shows the whole scene; its 6 steps are listed below.

Every step as text
  1. Three elements. std::vector<int> marks{71, 64, 88}; makes a vector of three ints from the braced list. They sit side by side, at indexes 0, 1 and 2.
  2. A fourth at the end. push_back(92) adds 92 after the last element, at index 3. The vector makes room by itself when its memory is full; the next section shows how it does that.
  3. A fifth. push_back(57) adds 57 at index 4, and std::println printed the whole vector: marks: [71, 64, 88, 92, 57].
  4. The two ends. size() is 5, front() is 71 and back() is 57, as the program printed: size 5, first 71, last 57. The valid indexes are 0 to size() - 1, that is 0 to 4.
  5. Every element in order. The range-for loop gives m each element in turn: 71 + 64 + 88 + 92 + 57 = 372, and the program printed total 372. No index appears anywhere in the loop.
  6. By position. The index loop runs i, a std::size_t, from 0 while i < marks.size(). Only marks[4] is below 60, so the program printed marks[4] = 57 needs a second attempt.

Every value in the figure is one the program printed: each push_back added one element at the end, and the indexes ran from 0 to 4.

Two details catch almost everyone once:

  • Parentheses and braces mean different things. std::vector<int> v(5) holds five zeros and v(5, 7) holds five sevens, because parentheses pass a count and a value. std::vector<int> v{5} holds a single element, the number 5: braces list the elements.
  • emplace_back builds the element in place. names.emplace_back(3, 'a') passes its arguments to the std::string constructor, which builds "aaa" directly in the vector’s memory. push_back("Ravi") first makes a temporary string and then moves it in. For values you already have, push_back is just as good.

Key idea

A vector’s elements are numbered from 0 to size() - 1: braces list them, parentheses give a count, and push_back adds one at the end.

Checkpoint

Check: Creating and reading a vector

  1. Question 1 of 2 What does std::vector<int> v(3, 9); hold?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: [9, 9, 9]

    With parentheses the first number is how many elements there are and the second is their value, as v(5, 7) gave [7, 7, 7, 7, 7] in basics.cpp. With braces every number is an element.

  2. Question 2 of 2 What do these lines print?

    Read the code, then choose one answer.

    std::vector<std::string> names;
    names.emplace_back(2, 'z');
    names.push_back("Ravi");
    std::println("{}", names);
    A hint

    emplace_back passes its arguments to the constructor of the element type.

    Show the answer: Question 2 of 2

    Answer: ["zz", "Ravi"]

    emplace_back(args…) builds one element from its arguments, here std::string(2, 'z'), which is "zz", just as basics.cpp built "aaa" from (3, 'a'). push_back adds a value you already have, and std::println prints the strings in quotes.

Size counts the elements, capacity the slots of its buffer

A vector has two numbers. Its size is how many elements it holds. Its capacity is how many elements its buffer, the block of memory where the elements live, has room for. The vector object itself is small and fixed; the buffer is allocated on the heap:

A vector object of three pointers points to a heap buffer of 8 int slots: 5 hold elements, 3 are spare capacity.the vector object: 24 bytesits buffer on the heap: 32 bytesbeginendsize 5buffer endcapacity 8[0]71[1]64[2]88[3]92[4]57sparesparesparebegin points to [0]

A std::vector<int> with size 5 and capacity 8

Text description of the diagram

The diagram shows the two parts of a std::vector<int> called marks.

  1. The vector object itself is 24 bytes on a 64-bit computer. Both standard libraries store three pointers in it: where the buffer begins, where the elements end, and where the buffer ends. The size (5) and the capacity (8) are worked out from them.
  2. The first pointer leads to the buffer, a block of memory on the heap with room for 8 ints, 32 bytes in all.
  3. The first 5 slots hold the elements 71, 64, 88, 92 and 57, at indexes 0 to 4. The last 3 slots are spare capacity: allocated, but not elements yet.

push_back puts the next element into the first spare slot without allocating. When no slot is spare, the vector has to allocate a bigger buffer.

While there is spare capacity, push_back just builds the new element in the next free slot. When the buffer is full, it has to allocate a bigger buffer, put the new element and every old one into it, and free the old buffer. The standard does not say how much bigger. It only requires adding at the end to take amortised constant time: A cost that is constant on average over a long run of calls, although one call may take much longer. A push_back sometimes moves every element, but because the capacity doubles, 1,000 calls moved 1,023 elements in all., which rules out growing by a fixed number of slots. This program records what the libraries really do:

growth.cpp C++ · growth.cpp
// Watches a vector grow: its capacity after each push_back that changes it, and how many elements had to move.
#include <cstddef>
#include <print>
#include <vector>

int main() {
    std::vector<int> v;
    std::println("empty: size {}, capacity {}, the vector object itself is {} bytes", v.size(), v.capacity(), sizeof v);
    int allocations = 0;
    std::size_t moved = 0;
    for (int i = 1; i <= 1000; ++i) {
        std::size_t old_capacity = v.capacity();
        std::size_t old_size = v.size();
        v.push_back(i);
        if (v.capacity() != old_capacity) {      // push_back needed a bigger buffer
            ++allocations;
            moved += old_size;                   // every element so far went to the new buffer
            std::println("size {:4}  capacity {:4}", v.size(), v.capacity());
        }
    }
    std::println("1000 push_backs: {} allocations, {} elements moved", allocations, moved);

    std::vector<int> w;
    w.reserve(1000);                             // one allocation, big enough for everything
    const int* buffer = w.data();
    for (int i = 1; i <= 1000; ++i) w.push_back(i);
    std::println("with reserve(1000) first: capacity {}, same buffer all along: {}", w.capacity(), w.data() == buffer);
    std::println("still {} bytes for the vector object, {} bytes in its buffer", sizeof w, w.capacity() * sizeof(int));
}
Growth with libc++, compared with libstdc++ Python · growth_session.py
from session import run

# The growth of one vector, recorded with libc++ (Apple clang) and compared with libstdc++ (GCC 16).
run("""
clang++ -std=c++23 -Wall -Wextra growth.cpp -o growth
./growth
g++-16 -std=c++23 -Wall -Wextra growth.cpp -o growth-gcc
./growth > libcxx.txt
./growth-gcc > libstdcxx.txt
diff libcxx.txt libstdcxx.txt && echo "libstdc++ printed exactly the same"
""")

Output

$ clang++ -std=c++23 -Wall -Wextra growth.cpp -o growth
$ ./growth
empty: size 0, capacity 0, the vector object itself is 24 bytes
size    1  capacity    1
size    2  capacity    2
size    3  capacity    4
size    5  capacity    8
size    9  capacity   16
size   17  capacity   32
size   33  capacity   64
size   65  capacity  128
size  129  capacity  256
size  257  capacity  512
size  513  capacity 1024
1000 push_backs: 11 allocations, 1023 elements moved
with reserve(1000) first: capacity 1000, same buffer all along: true
still 24 bytes for the vector object, 4000 bytes in its buffer
$ g++-16 -std=c++23 -Wall -Wextra growth.cpp -o growth-gcc
$ ./growth > libcxx.txt
$ ./growth-gcc > libstdcxx.txt
$ diff libcxx.txt libstdcxx.txt && echo "libstdc++ printed exactly the same"
libstdc++ printed exactly the same

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 growth_session.py

Both libraries double the capacity whenever the buffer is full: 1, 2, 4 and so on up to 1,024. For 1,000 push_back calls that is 11 allocations, and the 10 that replaced an existing buffer moved 1 + 2 + 4 + … + 512 = 1,023 elements, about one move per element. Doubling is what keeps the cost down: each reallocation: What a std::vector does when an element must be added and its buffer is full: it allocates a larger buffer, moves the elements into it and frees the old one, so every pointer, reference and iterator to the elements dangles. moves one element more than all the earlier ones together, so the total stays below the final capacity, and so below twice the size, however long the vector grows.

Step through the calls that changed the capacity, from the first element to the thousandth, and then the vector that reserved its room first:

Interactive · stage by stage The 11 allocations of 1,000 push_back calls Step through the calls that changed the capacity, then the vector that reserved its room first. Each stage is one allocation, and its sub-label says how many elements it moved.
The 11 allocations of 1,000 push_back calls, step 8 of 8. Showing Call 1: capacity 1, Call 2: capacity 2, Call 3: capacity 4, Call 5: capacity 8, Call 9: capacity 16, Calls 17 to 257, Call 513: capacity 1024, reserve(1000) first. In focus: reserve(1000) first.Call 1: capacity 1up from 0, nothing to moveCall 2: capacity 2moves 1 elementCall 3: capacity 4moves 2 elementsCall 5: capacity 8moves 4 elementsCall 9: capacity 16moves 8 elementsCalls 17 to 257capacity 32 up to 512Call 513: capacity 1024moves 512 elementsreserve(1000) firstone allocation, no moves

The drawing shows the whole scene; its 8 steps are listed below.

Every step as text
  1. The first element. The empty vector has capacity 0, so the first push_back has to allocate. The program printed size 1, capacity 1: one slot, and nothing to move yet.
  2. Full at size 1. The second call finds size 1 equal to capacity 1. It allocates a buffer of 2 slots, moves the 1 element into it and frees the old buffer; the new element goes into the new buffer.
  3. Doubling again. Call 3 finds 2 of 2 slots used: capacity 4, and 2 elements moved. Call 4 then fits into the spare slot without allocating anything.
  4. Room for 8. Call 5 moves 4 elements into 8 slots, so calls 6, 7 and 8 fit. Each new buffer is twice the size of the one before it.
  5. Room for 16. Call 9 moves 8 elements into 16 slots. The four reallocations so far moved 1 + 2 + 4 + 8 = 15 elements, fewer than the 16 slots of this buffer.
  6. Five more doublings. Calls 17, 33, 65, 129 and 257 raise the capacity to 32, 64, 128, 256 and 512, and move 16, 32, 64, 128 and 256 elements.
  7. The last allocation. Call 513 moves 512 elements into 1,024 slots, and calls 514 to 1,000 all fit. In all: 11 allocations and 1 + 2 + 4 + … + 512 = 1,023 elements moved, about one per call.
  8. Reserving first. The second vector called reserve(1000) before its loop: one allocation of 1,000 slots, no element ever moved, and the program printed same buffer all along: true.

Only 11 of the 1,000 calls allocated. The other 989 found a spare slot and only had to build their element there.

When you know the final size, reserve(n) allocates once. The second vector reserved 1,000 slots and kept the same buffer through all 1,000 calls. The vector object stayed 24 bytes throughout: both libraries store three pointers in it, and the elements live in the buffer, 4,000 bytes here.

Three more functions change these numbers:

  • resize(n) changes the size: it adds value-initialised elements, zeros for int, or removes elements from the end. reserve(n) changes only the capacity and never adds elements.
  • clear() removes every element but keeps the buffer, so the capacity stays the same.
  • shrink_to_fit() asks the vector to give its spare capacity back. The standard calls it a non-binding request, so a library may keep the memory.

Key idea

Size counts elements and capacity counts slots. A full buffer doubles, so 1,000 push_back calls cost 11 allocations, and reserve(n) makes it one allocation when you know n.

Checkpoint

Check: Size, capacity and doubling

  1. Question 1 of 2 An empty std::vector<int> gets push_back calls one at a time. How many elements does the ninth call move into a new buffer?

    Type a number.

    A hint

    Before the ninth call, how many elements does the vector hold, and how many slots has its buffer?

    Show the answer: Question 1 of 2

    Answer: 8 elements

    After call 5 the capacity is 8, so calls 6, 7 and 8 fit. The ninth call finds 8 of 8 slots used: it allocates 16 slots and moves all 8 elements, and growth.cpp printed size 9, capacity 16.

  2. Question 2 of 2 std::vector<int> v; v.reserve(10); What are v.size() and v.capacity() now?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: Size 0, capacity at least 10

    reserve(n) raises the capacity to at least n and leaves the size alone; resize(n) changes the size. The second vector of growth.cpp reserved 1,000 slots and kept the same buffer through all 1,000 push_back calls.

Growing moves the elements, so old references dangle

Reallocation has a consequence that causes many C++ bugs. A pointer, a reference or an iterator to an element points into the buffer, and after a reallocation that buffer is gone:

push_back on a full vector moves 10, 20 and 30 to a new buffer and frees the old one, where a reference taken earlier still points.int& first = scores[0]taken before push_backold buffer, fullnew buffer: capacity 610203010203040sparesparestill refers to the old [0]push_back(40): allocate 6 slots,move 10, 20, 30, add 40,then free the old buffer

Why a reference into a vector dangles after push_back

Text description of the diagram

The diagram follows the vector scores from the lesson's example, which holds 10, 20 and 30 with capacity 3, so its buffer is full.

  1. Before the push_back, the reference first is bound to scores[0], the slot holding 10 in the old buffer.
  2. push_back(40) needs a fourth slot. The vector allocates a new buffer with room for 6 ints, moves 10, 20 and 30 into it, adds 40 after them and frees the old buffer.
  3. The vector now uses only the new buffer, but first still refers to the first slot of the old one, which is freed memory. Reading through first is undefined behaviour: AddressSanitizer reports it as a heap-use-after-free.
dangling.cpp C++ · dangling.cpp
// A reference into a vector, kept across a push_back that reallocates.
#include <print>
#include <vector>

int main() {
    std::vector<int> scores{10, 20, 30};
    int& first = scores[0];          // refers to the element inside the vector's buffer
    std::println("capacity before: {}", scores.capacity());
    scores.push_back(40);            // the buffer is full: a new one is allocated, the old one freed
    std::println("capacity after: {}", scores.capacity());
    std::println("first = {}", first);   // reads the freed buffer: undefined behaviour
}

The compiler accepts this program, and without help the mistake is invisible: the last line reads whatever happens to be in the freed memory. sanitizer: A compiler option, such as -fsanitize=address or -fsanitize=undefined, that builds extra checks into a program, so that memory errors and undefined behaviour are reported, with their source line, while it runs. More in “Finding memory bugs with AddressSanitizer and UBSan”, a checker built into Clang and GCC that you switch on with -fsanitize=address, stops the program at the bad read:

AddressSanitizer catches the read Python · dangling_session.py
from session import run

# AddressSanitizer catches the read through the old reference. grep keeps the key lines of its report, and sed hides
# the addresses, which change on every run.
run("""
clang++ -std=c++23 -g -fsanitize=address dangling.cpp -o dangling
ASAN_OPTIONS=symbolize=0 ./dangling 2>&1 | grep -E "ERROR|of size|located|freed by|allocated by" | sed -E 's/==[0-9]+==//; s/0x[0-9a-f]+/0x…/g'
""")

Output

$ clang++ -std=c++23 -g -fsanitize=address dangling.cpp -o dangling
$ ASAN_OPTIONS=symbolize=0 ./dangling 2>&1 | grep -E "ERROR|of size|located|freed by|allocated by" | sed -E 's/==[0-9]+==//; s/0x[0-9a-f]+/0x…/g'
ERROR: AddressSanitizer: heap-use-after-free on address 0x… at pc 0x… bp 0x… sp 0x…
READ of size 4 at 0x… thread T0
0x… is located 0 bytes inside of 12-byte region [0x…,0x…)
freed by thread T0 here:
previously allocated by thread T0 here:

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 dangling_session.py

Step through the program in time order and watch where first points when line 11 reads it:

Interactive · step by step Where first points while dangling.cpp runs Step through the program. The left column is the memory of the vector, the right one the names; an arrow shows what each name points into.
Where first points while dangling.cpp runs, step 5 of 5. Showing old buffer: 3 ints (freed), the vector scores (size 4, capacity 6), int& first (refers to the 10), new buffer: 6 slots (10 20 30 40, 2 spare). In focus: int& first, old buffer: 3 ints.refers to [0]its bufferold buffer: 3 intsfreedthe vector scoressize 4, capacity 6int& firstrefers to the 10new buffer: 6 slots10 20 30 40, 2 spareread after it was freed

The drawing shows the whole scene; its 5 steps are listed below.

Every step as text
  1. A full buffer. scores{10, 20, 30} holds 3 ints in a buffer of exactly 3 slots, 12 bytes. The buffer is full: size equals capacity.
  2. A reference into it. int& first = scores[0]; binds first to the slot that holds 10. The reference points into the buffer, not into the vector object.
  3. A bigger buffer. push_back(40) needs a fourth slot. The vector allocates a new buffer with room for 6 ints and moves 10, 20 and 30 into it; 40 goes after them.
  4. The old one is freed. The vector now uses the new buffer and frees the old one. Nothing updates first: it still refers to the first slot of the freed buffer.
  5. Line 11 reads it. Line 11 reads first. AddressSanitizer stopped the program at that read: a heap-use-after-free, 0 bytes inside a 12-byte region, the old buffer of three ints.

No single line is wrong on its own: the bug is that first was kept across a call that moved the elements.

The report names the bug, a heap-use-after-free, and says the read landed inside a 12-byte region that the program had already freed: the old buffer of three int values. The rule, from the standard’s section on vector modifiers: a call that makes the size larger than the capacity reallocates, and reallocation invalidates every reference, pointer and iterator to the elements. push_back, emplace_back, insert, resize and reserve can all do it. Without a reallocation, an insertion still invalidates those at or after the insertion point. Safe habits:

  • Keep an index instead of a pointer or reference. scores[0] is still the first element after any growth.
  • Take references just before you use them, after the last call that can add elements.
  • Never add elements to a vector while a range-for loop is walking over it: the loop’s hidden iterators dangle in the same way.

Key idea

Any call that can grow a vector can move its elements: keep indexes across such calls, and take references only after the last of them.

Checkpoint

Check: References after a reallocation

  1. Question 1 of 2 scores is full when scores.push_back(40) runs. Which of these, saved before the call, still gives you the first element afterwards?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: The index 0, used as scores[0]

    Reallocation moves the elements into a new buffer and frees the old one, so every pointer, reference and iterator into the old one dangles. An index survives any growth.

  2. Question 2 of 2 A vector has size 5 and capacity 10, and the iterator it points to v[3]. Then v.insert(v.begin() + 1, 7); runs. Can it still be used?

    Choose one answer.

    A hint

    Nothing reallocates here. Which elements had to move to make room for 7?

    Show the answer: Question 2 of 2

    Answer: No, because the elements from index 1 on moved, and it points after the insertion point

    With spare capacity, insert keeps the buffer, but every element from the insertion point on moves one place to the right. The standard invalidates the iterators and references at or after that point, so it, at index 3, is invalid; one that pointed before index 1 would still be valid.

Reading past the end is undefined: one bug, four results

marks[i] does not check i. The standard states a precondition, i < size(), and a call that breaks it has undefined behaviour: What a program does when it breaks a rule for which the C++ standard sets no requirements, such as reading past the end of an array. The compiler may assume it never happens, so the result can change with the compiler and the optimisation level. More in “Object lifetime and undefined behaviour in C++”: the standard makes no promise about what happens. Here is the most common way to break it, a loop that runs one step too far:

oob.cpp C++ · oob.cpp
// An off-by-one loop: i <= size() reads one element past the end of the vector.
#include <cstddef>
#include <print>
#include <vector>

int total(const std::vector<int>& marks) {
    int sum = 0;
    for (std::size_t i = 0; i <= marks.size(); ++i) sum += marks[i];   // bug: should be i < marks.size()
    return sum;
}

int main() {
    std::vector<int> marks{71, 64, 88, 92, 57};
    std::println("total = {}", total(marks));   // the right answer is 372
}

Step through total() on the five marks and watch the test that lets i reach 5:

Interactive · stage by stage The off-by-one loop of oob.cpp, pass by pass Step through total() on five marks. The test runs before every pass, and the sub-labels show i and the sum so far.
The off-by-one loop of oob.cpp, pass by pass, step 7 of 7. Showing i <= marks.size() ? (i is 5: still true), sum += marks[i] (372, 0, a stop or 372), ++i. In focus: sum += marks[i].test againi <= marks.size() ?i is 5: still truesum += marks[i]372, 0, a stop or 372++ithe next index

The drawing shows the whole scene; its 7 steps are listed below.

Every step as text
  1. Pass 1: i is 0. 0 <= 5 is true, so the loop reads marks[0], 71: sum is 71.
  2. Pass 2: i is 1. 1 <= 5: the loop reads marks[1], 64, and sum becomes 135.
  3. Pass 3: i is 2. marks[2] is 88, and sum becomes 223.
  4. Pass 4: i is 3. marks[3] is 92, and sum becomes 315.
  5. Pass 5: i is 4. marks[4] is 57, the last element, and sum becomes 372: the right total. A loop with i < marks.size() would stop after this pass.
  6. Pass 6: i is 5. 5 <= 5 is still true, so the loop reads marks[5], one place past the last element. That read breaks the precondition i < size(): undefined behaviour.
  7. Four builds, four results. What the sixth pass did depended on the build: Clang without optimisation printed 372, Clang with -O2 printed 0, GCC without optimisation stopped at an assertion, and GCC with -O2 printed 372.

The first five passes added up to 372, the right total, and the sixth read an element that does not exist. Here is what that read did in four builds:

Two compilers, without and with -O2 Python · oob_session.py
from session import run

# One program with an off-by-one loop, built four ways: two compilers, without and with optimisation.
run("""
clang++ -std=c++23 -O0 oob.cpp -o oob-clang-O0
./oob-clang-O0
clang++ -std=c++23 -O2 oob.cpp -o oob-clang-O2
./oob-clang-O2
g++-16 -std=c++23 -O0 oob.cpp -o oob-gcc-O0
./oob-gcc-O0
g++-16 -std=c++23 -O2 oob.cpp -o oob-gcc-O2
./oob-gcc-O2
""")

Output

$ clang++ -std=c++23 -O0 oob.cpp -o oob-clang-O0
$ ./oob-clang-O0
total = 372
$ clang++ -std=c++23 -O2 oob.cpp -o oob-clang-O2
$ ./oob-clang-O2
total = 0
$ g++-16 -std=c++23 -O0 oob.cpp -o oob-gcc-O0
$ ./oob-gcc-O0
/opt/homebrew/Cellar/gcc/16.2.0/include/c++/16/bits/stl_vector.h:1272: constexpr std::vector< <template-parameter-1-1>, <template-parameter-1-2> >::const_reference std::vector< <template-parameter-1-1>, <template-parameter-1-2> >::operator[](size_type) const [with _Tp = int; _Alloc = std::allocator<int>; const_reference = const int&; size_type = long unsigned int]: Assertion '__n < this->size()' failed.
[stopped by SIGABRT: a shell reports exit status 134]
$ g++-16 -std=c++23 -O2 oob.cpp -o oob-gcc-O2
$ ./oob-gcc-O2
total = 372

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 oob_session.py

The same source gave four results:

  • Clang without optimisation printed 372, the right total. The sixth read found a 0 in the memory just after the buffer, so the bug left no trace.
  • Clang with -O2 printed 0. The optimiser worked out the whole total while compiling, and one of the six values it adds does not exist, so the result had no defined value. Clang could print anything, and it printed 0.
  • GCC without optimisation stopped with a failed assertion. Since GCC 15, libstdc++ switches on its debug assertions in builds without optimisation; -D_GLIBCXX_NO_ASSERTIONS turns them off again.
  • GCC with -O2 printed 372, and an optimised build checks nothing.

A test that prints the right answer proves nothing about a bug like this one.

A loop condition with <= size()

for (std::size_t i = 0; i <= marks.size(); ++i) runs once more than there are elements. Write i < marks.size(), or loop with for (int m : marks), which has no index to get wrong.

Checkpoint

Check: Reading past the end

  1. Question 1 of 2 Which loop over the five marks of oob.cpp adds every mark exactly once?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: for (std::size_t i = 0; i < marks.size(); ++i) sum += marks[i];

    The valid indexes run from 0 to size() - 1, so the condition is i < marks.size(). A range-for, for (int m : marks), avoids the question altogether.

  2. Question 2 of 2 A test of total() passes on the Clang build without optimisation, which printed 372. What does that show?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: Nothing about the bug, because the read past the end is undefined behaviour

    Undefined behaviour means the standard promises nothing: the four builds of oob.cpp printed 372, printed 0, stopped at an assertion and printed 372. Only a check, such as at(), a hardened library or AddressSanitizer, finds the bug.

at(), a hardened library or AddressSanitizer catches the bad index

Each of these turns the same bug into an error you can see, at the faulty read:

oob_at.cpp C++ · oob_at.cpp
// The same off-by-one loop, with at() instead of [].
#include <cstddef>
#include <print>
#include <stdexcept>
#include <vector>

int total(const std::vector<int>& marks) {
    int sum = 0;
    for (std::size_t i = 0; i <= marks.size(); ++i) sum += marks.at(i);   // at() checks i < size()
    return sum;
}

int main() {
    std::vector<int> marks{71, 64, 88, 92, 57};
    try {
        std::println("total = {}", total(marks));
    } catch (const std::out_of_range& e) {
        std::println("caught std::out_of_range: {}", e.what());
    }
}
at(), hardened libraries and AddressSanitizer Python · checks_session.py
from session import run

# Three ways to catch the off-by-one read: at(), a hardened standard library and AddressSanitizer.
run("""
# 1. at() checks the index and throws std::out_of_range
clang++ -std=c++23 oob_at.cpp -o oob-at
./oob-at
g++-16 -std=c++23 oob_at.cpp -o oob-at-gcc
./oob-at-gcc
# 2. A hardened library checks operator[] itself, even with -O2
clang++ -std=c++23 -O2 -D_LIBCPP_HARDENING_MODE=_LIBCPP_HARDENING_MODE_FAST oob.cpp -o oob-fast
./oob-fast
clang++ -std=c++23 -O2 -D_LIBCPP_HARDENING_MODE=_LIBCPP_HARDENING_MODE_DEBUG oob.cpp -o oob-debug
./oob-debug
g++-16 -std=c++23 -O2 -D_GLIBCXX_ASSERTIONS oob.cpp -o oob-assertions
./oob-assertions
# 3. AddressSanitizer checks every memory access (key lines of its report, addresses hidden)
clang++ -std=c++23 -g -fsanitize=address oob.cpp -o oob-asan
ASAN_OPTIONS=symbolize=0 ./oob-asan 2>&1 | grep -E "ERROR|of size|located" | sed -E 's/==[0-9]+==//; s/0x[0-9a-f]+/0x…/g'
""")

Output

# 1. at() checks the index and throws std::out_of_range
$ clang++ -std=c++23 oob_at.cpp -o oob-at
$ ./oob-at
caught std::out_of_range: vector
$ g++-16 -std=c++23 oob_at.cpp -o oob-at-gcc
$ ./oob-at-gcc
caught std::out_of_range: vector::_M_range_check: __n (which is 5) >= this->size() (which is 5)
# 2. A hardened library checks operator[] itself, even with -O2
$ clang++ -std=c++23 -O2 -D_LIBCPP_HARDENING_MODE=_LIBCPP_HARDENING_MODE_FAST oob.cpp -o oob-fast
$ ./oob-fast
[stopped by SIGTRAP: a shell reports exit status 133]
$ clang++ -std=c++23 -O2 -D_LIBCPP_HARDENING_MODE=_LIBCPP_HARDENING_MODE_DEBUG oob.cpp -o oob-debug
$ ./oob-debug
/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/c++/v1/__vector/vector.h:419: libc++ Hardening assertion __n < size() failed: vector[] index out of bounds
[stopped by SIGABRT: a shell reports exit status 134]
$ g++-16 -std=c++23 -O2 -D_GLIBCXX_ASSERTIONS oob.cpp -o oob-assertions
$ ./oob-assertions
/opt/homebrew/Cellar/gcc/16.2.0/include/c++/16/bits/stl_vector.h:1272: constexpr std::vector< <template-parameter-1-1>, <template-parameter-1-2> >::const_reference std::vector< <template-parameter-1-1>, <template-parameter-1-2> >::operator[](size_type) const [with _Tp = int; _Alloc = std::allocator<int>; const_reference = const int&; size_type = long unsigned int]: Assertion '__n < this->size()' failed.
[stopped by SIGABRT: a shell reports exit status 134]
# 3. AddressSanitizer checks every memory access (key lines of its report, addresses hidden)
$ clang++ -std=c++23 -g -fsanitize=address oob.cpp -o oob-asan
$ ASAN_OPTIONS=symbolize=0 ./oob-asan 2>&1 | grep -E "ERROR|of size|located" | sed -E 's/==[0-9]+==//; s/0x[0-9a-f]+/0x…/g'
ERROR: AddressSanitizer: heap-buffer-overflow on address 0x… at pc 0x… bp 0x… sp 0x…
READ of size 4 at 0x… thread T0
0x… is located 0 bytes after 20-byte region [0x…,0x…)
allocated by thread T0 here:

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 checks_session.py

  1. at(i) checks every call and throws std::out_of_range, which the program can catch. The message is the library’s own: libc++ says only vector, while libstdc++ names the index and the size.
  2. A hardened standard library: A standard library that checks the preconditions of calls such as operator[] and front() while the program runs, and stops it when one fails, as libc++'s hardening modes and libstdc++ with _GLIBCXX_ASSERTIONS do. C++26 makes such hardened implementations part of the standard. checks operator[] itself, even in an optimised build. In libc++ you choose a hardening mode with -D_LIBCPP_HARDENING_MODE=…. The fast mode, which the libc++ documentation recommends for production, keeps only cheap checks and stops the program with a trap, without a message (SIGTRAP above). The debug mode prints the failed check first and is meant for testing. In libstdc++, -D_GLIBCXX_ASSERTIONS does the same job in any build.
  3. AddressSanitizer (ASan) checks every memory access, not just the library’s. Its report says the read was 0 bytes after a 20-byte region, the buffer of five int values. The Clang documentation puts its typical cost at twice the run time, so it is for testing, not for production.

Side by side, the three differ in what a bad index does, what else they find and what they cost:

Three ways to catch a bad index
Criterion v.at(i)Hardened libraryASan
Bad index ThrowsStops the programStops and reports
Finds Bad indexesLibrary misuseMost memory bugs
Cost TinyTinyAbout 2× the time
When to choose Input you rejectProductionTests

Version note

C++26 makes hardening part of the standard. A hardened implementation must check preconditions such as i < size() in operator[], and front() and back() on an empty container, and treat a failed check as a contract violation (paper P3471). How you switch hardening on is still up to each compiler and library.

Checkpoint

Check: at(), hardening and AddressSanitizer

  1. Question 1 of 2 What did the -O2 build with libc++'s fast hardening mode do when oob.cpp read marks[5]?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: It stopped with a trap, SIGTRAP, without a message

    libc++'s fast mode checks operator[] in optimised builds and stops with a trap; the session shows [stopped by SIGTRAP]. The debug mode printed the failed check, __n < size(), and stopped with SIGABRT.

  2. Question 2 of 2 AddressSanitizer reported that the bad read was 0 bytes after a 20-byte region. With 4-byte ints, how many elements did that buffer hold?

    Type a number.

    Show the answer: Question 2 of 2

    Answer: 5 elements

    20 ÷ 4 = 5: the buffer of the five marks. "0 bytes after" means the read began right at its end, at marks[5], the first int past the last element.

std::erase removes elements by value or by a test, in one pass

Since C++20, two functions remove elements by value or by a test, and return how many they removed:

erase.cpp C++ · erase.cpp
// Removing elements: std::erase and std::erase_if (C++20), and the erase-remove idiom they replace.
#include <algorithm>
#include <print>
#include <vector>

int main() {
    std::vector<int> runs{4, 0, 6, 0, 1, 0, 4};
    auto removed = std::erase(runs, 0);                          // every element equal to 0
    std::println("std::erase removed {}: {}", removed, runs);

    std::vector<int> marks{71, 34, 88, 29, 57};
    removed = std::erase_if(marks, [](int m) { return m < 35; }); // every element the test accepts
    std::println("std::erase_if removed {}: {}", removed, marks);

    std::vector<int> old_style{4, 0, 6, 0, 1, 0, 4};
    auto new_end = std::remove(old_style.begin(), old_style.end(), 0);  // moves the kept elements forward
    std::println("after std::remove: size {} (the tail is unspecified)", old_style.size());
    old_style.erase(new_end, old_style.end());                   // ...and erase() drops the tail
    std::println("erase-remove idiom: {}", old_style);

    std::vector<int> v{1, 2, 3, 4, 5, 6};
    for (auto it = v.begin(); it != v.end();) {                  // removing while looping:
        if (*it % 2 == 0) it = v.erase(it);                      // erase returns the next valid iterator
        else ++it;
    }
    std::println("odd numbers kept: {}", v);
}
Removing elements Python · erase_session.py
from session import run

run("""
clang++ -std=c++23 -Wall -Wextra erase.cpp -o erase
./erase
g++-16 -std=c++23 -Wall -Wextra erase.cpp -o erase-gcc
./erase-gcc
""")

Output

$ clang++ -std=c++23 -Wall -Wextra erase.cpp -o erase
$ ./erase
std::erase removed 3: [4, 6, 1, 4]
std::erase_if removed 2: [71, 88, 57]
after std::remove: size 7 (the tail is unspecified)
erase-remove idiom: [4, 6, 1, 4]
odd numbers kept: [1, 3, 5]
$ g++-16 -std=c++23 -Wall -Wextra erase.cpp -o erase-gcc
$ ./erase-gcc
std::erase removed 3: [4, 6, 1, 4]
std::erase_if removed 2: [71, 88, 57]
after std::remove: size 7 (the tail is unspecified)
erase-remove idiom: [4, 6, 1, 4]
odd numbers kept: [1, 3, 5]

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 erase_session.py

  • std::erase(runs, 0) removes every element equal to 0.
  • std::erase_if(marks, test) removes every element for which the test returns true. The test here is a lambda, a small function written in place; lambdas have a lesson of their own.
  • Older code writes the erase-remove idiom: The older way to remove elements by value: std::remove moves the elements to keep to the front and returns where they end, and erase then cuts off the rest. C++20's std::erase and std::erase_if do both steps in one call.. std::remove moves the elements to keep to the front and returns where they end, without changing the size (still 7 in the output), and erase then cuts off the tail. The standard defines std::erase as exactly these two steps, so the new form is never slower, and it is harder to get wrong.
  • To remove elements during a loop, use the iterator that v.erase(it) returns. It points to the element after the removed one, while it itself is invalid after the call.

Step through the idiom on the seven values of old_style, then std::erase on the same values in runs:

Interactive · stage by stage Removing the zeros of 4, 0, 6, 0, 1, 0, 4 two ways Step through the erase-remove idiom, then std::erase. Each stage is one call, and its sub-label shows the values and the size after it.
Removing the zeros of 4, 0, 6, 0, 1, 0, 4 two ways, step 5 of 5. Showing old_style: 7 elements, std::remove(…, 0) (4 6 1 4, then the tail), size() is still 7 (size 7; 4 to 6 unknown), erase(new_end, end()) (4 6 1 4, size 4), std::erase(runs, 0) (removed 3: 4 6 1 4). In focus: std::erase(runs, 0).old_style: 7 elements4 0 6 0 1 0 4std::remove(…, 0)4 6 1 4, then the tailsize() is still 7size 7; 4 to 6 unknownerase(new_end, end())4 6 1 4, size 4std::erase(runs, 0)removed 3: 4 6 1 4

The drawing shows the whole scene; its 5 steps are listed below.

Every step as text
  1. Three zeros. old_style holds 4, 0, 6, 0, 1, 0 and 4, seven elements of which three are 0.
  2. The kept values move up. std::remove keeps every element that is not 0 and moves each one forward, in order, over the zeros: 4 stays at index 0, 6 moves to 1, 1 to 2 and the last 4 to 3. It returns new_end, the position after them.
  3. Nothing was removed yet. std::remove receives only iterators, so it cannot change the size. The program printed size 7: indexes 4 to 6 still exist, holding values the standard leaves unspecified.
  4. The tail goes. old_style.erase(new_end, old_style.end()) destroys the three elements from new_end to the end, and the program printed erase-remove idiom: [4, 6, 1, 4].
  5. One call instead. std::erase(runs, 0) does both steps on the same seven values and returns how many it removed: the program printed std::erase removed 3: [4, 6, 1, 4].

Both ways end with [4, 6, 1, 4]; only std::erase also told the program that it removed 3 elements.

Each removal moves every later element one place forward, so removing from the front of a large vector is slow. One std::erase_if pass moves each element at most once, however many it removes.

Checkpoint

Check: std::erase and std::erase_if

  1. Question 1 of 2 std::remove(v.begin(), v.end(), 0) runs on a vector of 7 ints, 3 of them 0. What is v.size() right after the call?

    Type a number.

    A hint

    What does std::remove receive, the vector or two iterators?

    Show the answer: Question 1 of 2

    Answer: 7 elements

    std::remove only moves the elements to keep to the front and returns where they end; it receives iterators and cannot change the size. erase.cpp printed size 7 (the tail is unspecified).

  2. Question 2 of 2 Which loop removes the even numbers of v without using an invalid iterator?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: for (auto it = v.begin(); it != v.end();) { if (*it % 2 == 0) it = v.erase(it); else ++it; }

    Use the iterator that erase returns and step on only when nothing was erased, as erase.cpp did to keep [1, 3, 5]. Simpler still: std::erase_if(v, [](int x) { return x % 2 == 0; }).

Practise: two vector functions

Write two functions in the file below, then build and run it:

  1. remove_duplicates_keep_order(v) keeps the first copy of each value, in the original order: {3, 1, 3, 2, 1} becomes {3, 1, 2}.
  2. rotate_left(v, k) moves the first k elements to the end: {1, 2, 3, 4, 5} with k = 2 becomes {3, 4, 5, 1, 2}. A k larger than the size wraps around, and an empty vector must not crash.
vector_exercise.cpp C++ · vector_exercise.cpp
// Exercise: write the two functions, then build and run this file. Every check must say "ok".
//   clang++ -std=c++23 -Wall -Wextra -fsanitize=address,undefined vector_exercise.cpp -o vector_exercise
//   ./vector_exercise
#include <cstddef>
#include <print>
#include <vector>

// Removes every repeated value, keeping the first copy of each value in its original place:
// {3, 1, 3, 2, 1} becomes {3, 1, 2}.
void remove_duplicates_keep_order(std::vector<int>& v) {
    // your code here
}

// Moves the first k elements to the end, keeping the order of both parts:
// {1, 2, 3, 4, 5} with k = 2 becomes {3, 4, 5, 1, 2}. A k larger than the size wraps around.
void rotate_left(std::vector<int>& v, std::size_t k) {
    // your code here
}

int failures = 0;

void check(bool passed, const char* what) {
    std::println("{}  {}", passed ? "ok    " : "FAILED", what);
    if (!passed) ++failures;
}

int main() {
    std::vector<int> a{3, 1, 3, 2, 1};
    remove_duplicates_keep_order(a);
    check(a == std::vector<int>{3, 1, 2}, "{3, 1, 3, 2, 1} keeps {3, 1, 2}");

    std::vector<int> b{7, 7, 7};
    remove_duplicates_keep_order(b);
    check(b == std::vector<int>{7}, "{7, 7, 7} keeps {7}");

    std::vector<int> c;
    remove_duplicates_keep_order(c);
    check(c.empty(), "an empty vector stays empty");

    std::vector<int> d{1, 2, 3, 4, 5};
    rotate_left(d, 2);
    check(d == std::vector<int>{3, 4, 5, 1, 2}, "rotate_left({1, 2, 3, 4, 5}, 2) gives {3, 4, 5, 1, 2}");

    std::vector<int> e{1, 2, 3};
    rotate_left(e, 4);
    check(e == std::vector<int>{2, 3, 1}, "k = 4 on three elements works like k = 1");

    std::vector<int> f;
    rotate_left(f, 3);
    check(f.empty(), "rotating an empty vector does nothing (and does not crash)");

    std::vector<int> big(1'000'000);
    for (std::size_t i = 0; i < big.size(); ++i) big[i] = static_cast<int>(i);
    rotate_left(big, 999'999);
    check(big.front() == 999'999 && big[1] == 0 && big.back() == 999'998, "one million elements rotate by 999,999 quickly");

    std::vector<int> many;
    for (int i = 0; i < 100'000; ++i) many.push_back(i % 100);
    remove_duplicates_keep_order(many);
    check(many.size() == 100 && many.front() == 0 && many.back() == 99, "100,000 values with 100 distinct keep 0 to 99");

    std::println("{} of 8 checks failed", failures);
    return failures == 0 ? 0 : 1;
}

As it starts, the functions do nothing, so six of the eight checks fail:

The starting point Python · exercise_session.py
from session import run

# The exercise as it starts: the two functions do nothing yet, so most checks fail.
run("""
clang++ -std=c++23 -Wall -Wextra -fsanitize=address,undefined vector_exercise.cpp -o vector_exercise
./vector_exercise
""")

Output

$ clang++ -std=c++23 -Wall -Wextra -fsanitize=address,undefined vector_exercise.cpp -o vector_exercise
vector_exercise.cpp:10:53: warning: unused parameter 'v' [-Wunused-parameter]
   10 | void remove_duplicates_keep_order(std::vector<int>& v) {
      |                                                     ^
vector_exercise.cpp:16:36: warning: unused parameter 'v' [-Wunused-parameter]
   16 | void rotate_left(std::vector<int>& v, std::size_t k) {
      |                                    ^
vector_exercise.cpp:16:51: warning: unused parameter 'k' [-Wunused-parameter]
   16 | void rotate_left(std::vector<int>& v, std::size_t k) {
      |                                                   ^
3 warnings generated.
$ ./vector_exercise
FAILED  {3, 1, 3, 2, 1} keeps {3, 1, 2}
FAILED  {7, 7, 7} keeps {7}
ok      an empty vector stays empty
FAILED  rotate_left({1, 2, 3, 4, 5}, 2) gives {3, 4, 5, 1, 2}
FAILED  k = 4 on three elements works like k = 1
ok      rotating an empty vector does nothing (and does not crash)
FAILED  one million elements rotate by 999,999 quickly
FAILED  100,000 values with 100 distinct keep 0 to 99
6 of 8 checks failed
[exit status 1]

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 exercise_session.py

You are done when the program prints 0 of 8 checks failed and the sanitizers report nothing. The warnings about unused parameters disappear once your code uses them. Hints: std::find from <algorithm> tells you whether a value is already among the ones kept; k % v.size() reduces k, but only when the vector is not empty; and <algorithm> also has std::rotate. The checks with a million and with 100,000 elements catch solutions that are far too slow, such as one that rotates by a single place, k times over.

When the eight checks pass, quiz yourself on growth, invalidation, bounds and erasing. Your weakest idea comes up first, and each answer you choose is explained on the spot:

Practice that adapts to you

Practise this lesson

18 questions about 6 ideas of this lesson. Each answer is explained at once, and what you get right is kept in this browser.

  1. Question 1 of 18 What does std::vector<int> v{4}; contain?

    Choose one answer.

    Show the answer: Question 1 of 18

    Answer: One element, the number 4

    Braces with values make those values the elements, so v{4} holds the single number 4. Parentheses take a count: std::vector<int> v(4) holds four zeros. Room without elements is what reserve(4) gives.

  2. Question 2 of 18 A function only reads every name in std::vector<std::string> names. Which loop header reads each element in place, without copying it?

    Choose one answer.

    Show the answer: Question 2 of 18

    Answer: for (const std::string& name : names)

    For large elements such as strings, write for (const std::string& name : names): each element is read in place. A loop variable without & is a copy of the element.

  3. Question 3 of 18 Why does the index loop of basics.cpp declare i as std::size_t?

    Choose one answer.

    Show the answer: Question 3 of 18

    Answer: size() returns std::size_t, and with an int index, i < marks.size() would compare a signed number with an unsigned one

    size() returns std::size_t, an unsigned type. An int index makes the loop condition compare signed with unsigned, which -Wall -Wextra reports on both compilers; a std::size_t index avoids it.

  4. Question 4 of 18 An empty std::vector<int> gets 9 push_back calls. With libc++ or libstdc++, what is its capacity afterwards?

    Type a number.

    Show the answer: Question 4 of 18

    Answer: 16 elements

    Both libraries start with room for 1 and double whenever the buffer is full: 1, 2, 4, 8, then 16 when the ninth element arrives. The recording in the lesson shows the same steps up to 1,024.

  5. Question 5 of 18 Which call gives an empty std::vector<int> 100 elements, all 0?

    Choose one answer.

    Show the answer: Question 5 of 18

    Answer: v.resize(100)

    resize(n) changes the size, adding value-initialised elements (zeros for int) or removing them from the end. reserve(n) changes only the capacity, and clear() keeps the capacity but leaves no elements.

  6. Question 6 of 18 With the doubling that growth.cpp recorded, how many allocations do 2,000 push_back calls into an empty std::vector<int> make?

    Type a number.

    A hint

    List the capacities 1, 2, 4 … and find the first one that holds 2,000 elements.

    Show the answer: Question 6 of 18

    Answer: 12 allocations

    The capacities are 1, 2, 4, 8 … 1,024 and 2,048: twelve buffers, the last one allocated by call 1,025. Together they moved 1 + 2 + … + 1,024 = 2,047 elements, again about one move per call.

  7. Question 7 of 18 int& r = v[0]; is followed by v.push_back(7); when v.size() == v.capacity(). What is true of r afterwards?

    Choose one answer.

    Show the answer: Question 7 of 18

    Answer: It refers to freed memory, so reading it is undefined behaviour

    With no spare capacity, push_back allocates a new buffer, moves the elements there and frees the old buffer. The reference still names the slot in the old buffer. Take the reference again after the call, or keep the index instead.

  8. Question 8 of 18 Which of these calls can make a vector reallocate, and so invalidate every pointer, reference and iterator to its elements?

    Choose every answer that is right.

    Show the answer: Question 8 of 18

    Answer:

    • insert(pos, x)
    • reserve(n)
    • push_back(x)

    push_back, emplace_back, insert, resize and reserve can all make a vector reallocate. Reading with operator[], front(), back() or size() never does.

  9. Question 9 of 18 for (int x : v) if (x < 0) v.push_back(-x); What is wrong with this loop?

    Choose one answer.

    Show the answer: Question 9 of 18

    Answer: A push_back can reallocate and leave the loop's hidden iterators pointing into the freed buffer, which is undefined behaviour

    for (int x : v) works with two iterators taken before the first pass, v.begin() and v.end(). A push_back that reallocates frees the buffer they point into. Collect the new values in a second vector, and append them after the loop.

  10. Question 10 of 18 What does the C++ standard promise about marks[5] on a vector of five elements?

    Choose one answer.

    Show the answer: Question 10 of 18

    Answer: Nothing, because it breaks the precondition i < size(), so the behaviour is undefined

    operator[] has the precondition i < size(). A call that breaks it is undefined behaviour, so the four builds of oob.cpp were free to print 372, print 0 or stop.

  11. Question 11 of 18 Why did the GCC build without optimisation stop at an assertion, when the GCC -O2 build printed 372?

    Choose one answer.

    Show the answer: Question 11 of 18

    Answer: Since GCC 15, libstdc++ switches on its debug assertions in builds without optimisation

    libstdc++ has debug assertions, and since GCC 15 they are on in builds without optimisation; -D_GLIBCXX_NO_ASSERTIONS turns them off, and -D_GLIBCXX_ASSERTIONS turns them on in any build.

  12. Question 12 of 18 Why could Clang's -O2 build print 0 as the total, a value that no read of the marks produced?

    Choose one answer.

    Show the answer: Question 12 of 18

    Answer: The optimiser worked out the total while compiling, and with a read past the end the result had no defined value

    The standard makes no promise about a program with undefined behaviour, so the optimiser may assume it never happens. Clang computed the whole total while compiling, and the sixth value had no defined value, so the program could print anything; it printed 0.

  13. Question 13 of 18 Which of these report a read one past the end of a vector instead of silently returning a value?

    Choose every answer that is right.

    Show the answer: Question 13 of 18

    Answer:

    • v.at(i), which throws std::out_of_range
    • v[i] in a build with a hardened standard library, such as libc++'s fast mode
    • v[i] in a build with -fsanitize=address

    at() always checks. A hardened library adds the check to operator[] itself, and AddressSanitizer checks every memory access. An ordinary optimised build checks nothing: in the lesson's recordings the same bug printed 372 with GCC and 0 with Clang.

  14. Question 14 of 18 What does marks.at(5) do on a vector of five marks?

    Choose one answer.

    Show the answer: Question 14 of 18

    Answer: It throws std::out_of_range, which the program can catch

    at(i) checks the index on every call and throws std::out_of_range for a bad one. The message is the library's own: libc++ said only vector, libstdc++ named the index and the size.

  15. Question 15 of 18 Your test builds should say which check failed, and your production builds should keep the checks cheap. Which libc++ hardening modes fit?

    Choose one answer.

    Show the answer: Question 15 of 18

    Answer: The debug mode for the tests, and the fast mode for production

    Both modes check operator[] in optimised builds. The debug mode printed "libc++ Hardening assertion __n < size() failed" before stopping, which a test log needs; the fast mode stops with a trap and no message, and costs little.

  16. Question 16 of 18 std::vector<int> v{5, 0, 0, 3, 0}; What does std::erase(v, 0) return?

    Type a number.

    Show the answer: Question 16 of 18

    Answer: 3 elements

    std::erase removes every element equal to the value and returns how many it removed, here three zeros, leaving {5, 3}. std::erase_if does the same for every element a test accepts.

  17. Question 17 of 18 What do std::erase and std::erase_if return?

    Choose one answer.

    Show the answer: Question 17 of 18

    Answer: How many elements they removed

    std::erase(v, value) and std::erase_if(v, test) remove the matching elements in one pass and return how many they removed, which is why erase.cpp could print the count.

  18. Question 18 of 18 A vector of 1,000,000 ints must lose every even number. Why is one std::erase_if call much faster than calling v.erase(it) for each even element?

    Choose one answer.

    Show the answer: Question 18 of 18

    Answer: Each erase(it) moves every later element one place forward, while erase_if moves each element at most once

    Removing one element moves everything after it one place forward. erase_if moves each kept element forward once, so the whole job is a single pass over the million ints.

Interview questions

Fresher · What is the difference between a vector’s size and its capacity, and when does it matter?

The size is the number of elements the vector holds, and the capacity is the number of elements its current buffer has room for, so the capacity is never smaller than the size. Adding an element while there is spare capacity only builds it in the next slot. Adding one when size equals capacity reallocates: the vector allocates a bigger buffer (both libc++ and libstdc++ double it), moves every element there and frees the old buffer. That matters twice. It costs time, which reserve(n) avoids when you know the final size. And it invalidates every pointer, reference and iterator to the elements, so code that keeps one across a push_back can read freed memory. clear() sets the size to 0 but keeps the capacity.

Interviewers tend to follow this answer with two questions: what happens to the memory after clear(), and why the capacity doubles instead of growing by a fixed step. Answer both below; each option explains itself:

Checkpoint

Interview round: two follow-up questions

  1. Question 1 of 2 Follow-up: a vector of 1,000,000 ints is emptied with clear(). How much memory does it still hold, and how can it be handed back?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: Its buffer of at least 1,000,000 ints stays; shrink_to_fit() asks for it back, and destroying the vector frees it

    clear() destroys the elements but keeps the buffer for later push_back calls, so the capacity stays at least 1,000,000, about 4 MB of ints. shrink_to_fit() asks the library to release the spare capacity, and the standard calls that a non-binding request.

  2. Question 2 of 2 Follow-up: suppose a vector grew by a fixed 100 slots instead of doubling. How many elements would 1,000 push_back calls into an empty vector move in all?

    Type a number.

    A hint

    The buffer is full at 100, 200 … 900 elements, and each time every element moves.

    Show the answer: Question 2 of 2

    Answer: 4500 elements

    The first call allocates 100 slots. Calls 101, 201 … 901 each find the buffer full and move 100, 200 … 900 elements: 100 × (1 + 2 + … + 9) = 4,500, against the 1,023 that doubling moved. With a fixed step the moves grow with the square of the size, which is why amortised constant time rules it out.

Model answers open with any pass: ₹79 for 1 week ($2.99), one payment that never renews.

  1. Fresher to mid

    A trading service keeps a pointer to the best order, an element of a std::vector<Order> that new orders are appended to. It crashes only in the busiest hour of the day, and never in tests. What is the likely cause, how do you prove it, and how would you fix it?

    Model answer, Pro. Model answers open with any pass; prices are in the notice on this page. First step and follow-ups

  2. Mid to senior

    Your team argues about bounds checks in a service that indexes std::vectors with numbers taken from network messages. Some want at() everywhere, others want plain [] for speed. What policy would you set, and what does each option cost?

    Model answer, Pro. First step and follow-ups

Key takeaways

  • A vector keeps its elements side by side in one buffer on the heap; the vector object itself is three pointers, 24 bytes on a 64-bit computer. std::vector<int> v(5) holds five zeros; std::vector<int> v{5} holds one element, 5.
  • Size counts elements and capacity counts slots. Both libraries double the capacity when the buffer is full: 1,000 push_back calls made 11 allocations and moved 1,023 elements, and reserve(1000) made it one allocation and no moves.
  • Reallocation invalidates every pointer, reference and iterator to the elements. Keep indexes, or take references after the last call that can add elements.
  • v[i] with a bad index is undefined behaviour: the same bug printed 372, 0 or stopped the program, depending on the compiler and the optimisation level.
  • at() throws std::out_of_range; hardened libraries (libc++’s fast mode, libstdc++’s _GLIBCXX_ASSERTIONS) stop the program; AddressSanitizer reports every bad access while you test.
  • std::erase and std::erase_if (C++20) remove elements in one pass and return how many they removed.

Terms in this lesson

amortised constant time
A cost that is constant on average over a long run of calls, although one call may take much longer. A push_back sometimes moves every element, but because the capacity doubles, 1,000 calls moved 1,023 elements in all.
capacity
The number of elements a vector's buffer has room for, never less than its size. A push_back into a full buffer reallocates; reserve(n) raises the capacity to at least n without adding elements, and clear() leaves it as it was.
erase-remove idiom
The older way to remove elements by value: std::remove moves the elements to keep to the front and returns where they end, and erase then cuts off the rest. C++20's std::erase and std::erase_if do both steps in one call.
hardened standard library
A standard library that checks the preconditions of calls such as operator[] and front() while the program runs, and stops it when one fails, as libc++'s hardening modes and libstdc++ with _GLIBCXX_ASSERTIONS do. C++26 makes such hardened implementations part of the standard.
reallocation
What a std::vector does when an element must be added and its buffer is full: it allocates a larger buffer, moves the elements into it and frees the old one, so every pointer, reference and iterator to the elements dangles.

Corrections

  • The section on size and capacity no longer says that a full vector frees its old buffer before it adds the new element: both libraries build the new element first.

References

Report a problem with this lesson

Quick answers and tool search

Type to search tools or to get a quick answer, for example 18% of 2500. Use the up and down arrow keys to move through the results, Enter to choose, and Escape to close.