Skip to content
binshelf/ cpp

Search lessons

Type a C++ term, like vector, reference, unique_ptr or use-after-free.

    Lessons

    On this page

    1. Key terms
    2. In 30 seconds
    3. Creating a vector
    4. Adding elements: push_back and emplace_back
    5. Size, capacity and reserve
    6. Reaching elements: front, back and data
    7. Inserting and erasing in the middle
    8. Removing by value: std::erase and std::erase_if
    9. Invalidation: when changing a vector breaks references
    10. A grid: a vector of vectors or one flat vector
    11. std::vector<bool> is different
    12. Which one should I use?
    13. Under the hood
    14. Common pitfalls
    15. Writing into space made by reserve
    16. A bool& to an element of std::vector<bool>
    17. Try it yourself

    Module 3 · Strings and containers

    3.2vector

    The container you'll use most: create a std::vector, add and remove elements, plan its memory with reserve, store a grid in one flat vector, and know when changing a vector breaks references into it.

    About 25 minutesBeginner

    On this page
    1. Key terms
    2. In 30 seconds
    3. Creating a vector
    4. Adding elements: push_back and emplace_back
    5. Size, capacity and reserve
    6. Reaching elements: front, back and data
    7. Inserting and erasing in the middle
    8. Removing by value: std::erase and std::erase_if
    9. Invalidation: when changing a vector breaks references
    10. A grid: a vector of vectors or one flat vector
    11. std::vector<bool> is different
    12. Which one should I use?
    13. Under the hood
    14. Common pitfalls
    15. Writing into space made by reserve
    16. A bool& to an element of std::vector<bool>
    17. Try it yourself

    Key terms

    emplace_back(args…)
    Builds a new element at the end of a vector from the arguments you'd use to create one, instead of taking a finished element.
    capacity
    How many elements fit in a vector's current heap block. The size is how many it holds now.
    reserve(n)
    Makes sure a vector has room for at least n elements. It doesn't add any elements.
    resize(n)
    Changes the number of elements to n: adds new ones (zeros for numbers) at the end, or drops elements from the end.
    reallocation
    Moving a vector's elements to a new, bigger heap block because the old one is full, then freeing the old block.
    iterator
    An object that marks a position in a container. v.begin() is the first element, v.begin() + i is element i, and v.end() is the position just past the last. Lesson 7.2 covers iterators.
    predicate
    A function that answers yes or no about a value, by returning a bool.
    invalidate
    To make a reference, pointer or iterator into a container stale, because the element moved or was removed. Using it afterwards is undefined behavior.

    You’ve already used std::vector to hold a list of values, and Stack, heap and lifetime showed what it is: a small handle (24 bytes here) that owns a block of elements on the heap. A vector is the container you’ll reach for most often: the reads in a file, the scores of a model, the pixels of an image. This lesson covers what you do with one every day, and how to keep its memory under control.

    In 30 seconds

    • std::vector<T> holds any number of Ts side by side in one heap block. Add with push_back or emplace_back; remove with pop_back, erase, std::erase_if or clear.
    • When the block is full, the vector moves everything to a bigger one. If you know the count, reserve(n) asks for the whole block once.
    • Adding or removing elements can move them, which invalidates references and pointers into the vector.
    • For a grid, one flat vector indexed with row * width + column is usually better than a vector of vectors.

    Creating a vector

    The element type goes in the angle brackets. Braces list the elements; parentheses give a count, and optionally a value for every element:

    #include <print>
    #include <vector>
    
    std::vector<int> empty;
    std::vector<int> counts = {12, 7, 9, 3};
    std::vector<double> zeros(4);   // four 0.0s
    std::vector<char> gaps(3, '-'); // three '-'s
    std::println("{} {} {} {}", empty, counts, zeros, gaps);

    Output

    [] [12, 7, 9, 3] [0, 0, 0, 0] ['-', '-', '-']

    std::println shows characters and strings inside a container with quotes around them, so you can see spaces and empty strings.

    Braces and parentheses with the same numbers make different vectors:

    #include <print>
    #include <vector>
    
    std::vector<int> a(3, 7); // 3 elements, each 7
    std::vector<int> b{3, 7}; // 2 elements: 3 and 7
    std::println("{} {}", a, b);

    Output

    [7, 7, 7] [3, 7]

    Common pitfallBraces mean a list of elements

    For a vector, values in braces are always the elements: {3, 7} is the list 3, 7. To ask for a count, use parentheses: std::vector<int> v(3, 7).

    Adding elements: push_back and emplace_back

    push_back takes a finished element and puts a copy of it at the end, or moves it there if it’s a temporary. emplace_back takes the arguments you’d use to create an element, and builds it directly in the vector. pop_back removes the last element.

    #include <print>
    #include <string>
    #include <vector>
    
    std::vector<std::string> reads;
    reads.push_back("ACGT");    // builds a string, then moves it in
    reads.emplace_back(5, 'N'); // builds the string "NNNNN" in place
    std::string next = "TTGA";
    reads.push_back(next); // copies next; next is unchanged
    std::println("{}", reads);
    reads.pop_back();
    std::println("{} {}", reads, next);

    Output

    ["ACGT", "NNNNN", "TTGA"]
    ["ACGT", "NNNNN"] TTGA

    std::string(5, 'N') makes five Ns, so emplace_back(5, 'N') passes those two arguments on to build the string inside the vector. For numbers, push_back and emplace_back do the same thing. Moving, from Smart pointers, hands over an object’s heap block instead of copying it; Module 4 explains it in full.

    Size, capacity and reserve

    A vector’s size is how many elements it holds; its capacity is how many fit in its current block. When a push_back finds the block full, the vector does a reallocation: it gets a bigger block, moves the elements across and frees the old one. reserve(n) gets a block for n elements up front, so filling the vector needs no more reallocations:

    #include <print>
    #include <vector>
    
    std::vector<int> grown;
    int blocks = 0;
    for (int i = 0; i < 1000; ++i) {
        if (grown.size() == grown.capacity()) {
            ++blocks; // full: this push_back needs a new block
        }
        grown.push_back(i);
    }
    std::vector<int> planned;
    planned.reserve(1000);
    std::println("reserved: size {}, capacity {}", planned.size(),
                 planned.capacity());
    for (int i = 0; i < 1000; ++i) {
        planned.push_back(i);
    }
    std::println("grown: {} blocks, capacity {}", blocks, grown.capacity());
    std::println("planned: capacity {}", planned.capacity());

    Output

    reserved: size 0, capacity 1000
    grown: 11 blocks, capacity 1024
    planned: capacity 1000

    With GCC’s standard library the capacity doubles each time (1, 2, 4, … 1024), so grown got 11 blocks and moved its elements 10 times. planned got one block of exactly 1000.

    reserve adds room, not elements: after it, the size is still 0. To change the number of elements, use resize(n). It adds zeros (or a value you give) at the end, or drops elements from the end:

    #include <print>
    #include <vector>
    
    std::vector<int> v = {1, 2, 3};
    v.resize(5); // adds two 0s
    std::println("{}", v);
    v.resize(6, 9); // adds one 9
    std::println("{}", v);
    v.resize(2); // drops the last four
    std::println("{}, capacity {}", v, v.capacity());

    Output

    [1, 2, 3, 0, 0]
    [1, 2, 3, 0, 0, 9]
    [1, 2], capacity 6

    Shrinking never gives memory back: the block still has room for 6.

    Reaching elements: front, back and data

    front() and back() are the first and last elements. data() is a pointer to the first element, for code that takes a pointer and a count, such as a C library. The elements are contiguous, so [] on that pointer reaches the others:

    #include <print>
    #include <vector>
    
    std::vector<float> scores = {0.25f, 0.5f, 0.125f};
    std::println("first {}, last {}", scores.front(), scores.back());
    float* raw = scores.data();
    raw[1] = 0.75f;
    std::println("{}", scores);

    Output

    first 0.25, last 0.125
    [0.25, 0.75, 0.125]

    An empty vector has no first or last element, so front() and back() on one are undefined behavior. Check empty() first.

    Inserting and erasing in the middle

    insert and erase take a position, not an index. v.begin() is the position of the first element, and v.begin() + i is the position of element i. These position objects are called iterators; lesson 7.2, Iterators and algorithms, covers them.

    #include <print>
    #include <vector>
    
    std::vector<int> v = {10, 20, 30, 40};
    v.insert(v.begin() + 1, 15); // before element 1
    std::println("{}", v);
    v.erase(v.begin() + 3); // element 3, the 30
    std::println("{}", v);
    v.erase(v.begin(), v.begin() + 2); // elements 0 and 1
    std::println("{}", v);

    Output

    [10, 15, 20, 30, 40]
    [10, 15, 20, 40]
    [20, 40]

    The elements stay side by side, so inserting at position 1 shifts every later element one place to the right, and erasing shifts them back. Erasing the first of a million elements moves the other 999,999. Adding and removing at the end, with push_back and pop_back, shifts nothing. If the order doesn’t matter, remove an element by overwriting it with the last one and calling pop_back.

    Removing by value: std::erase and std::erase_if

    To remove every element equal to a value, call std::erase(v, value). To remove every element that passes a test, write the test as a predicate, a function that returns bool, and call std::erase_if(v, predicate). Both return how many elements they removed. clear() removes every element but keeps the heap block, so the capacity stays the same.

    #include <print>
    #include <vector>
    
    bool is_low(int quality) {
        return quality < 20;
    }
    
    int main() {
        std::vector<int> qualities = {30, 12, 35, 8, 40, 12};
        std::size_t removed = std::erase(qualities, 12);
        std::println("removed {}: {}", removed, qualities);
        std::erase_if(qualities, is_low);
        std::println("{}", qualities);
        qualities.clear();
        std::println("size {}, capacity {}", qualities.size(),
                     qualities.capacity());
    }

    Output

    removed 2: [30, 35, 8, 40]
    [30, 35, 40]
    size 0, capacity 6

    std::erase_if calls is_low on each element and removes the ones where it returns true. Lesson 7.1, Lambdas, shows how to write a test like this in place, without a named function.

    Modern C++New in C++20

    std::erase and std::erase_if arrived in C++20. Older code removes elements with v.erase(std::remove_if(v.begin(), v.end(), test), v.end()), which does the same thing in two steps.

    Invalidation: when changing a vector breaks references

    A reference, pointer or iterator into a vector is only valid while its element stays where it is. References showed the sanitizer catching a reference used after push_back moved the elements. The rules:

    • Anything that adds elements, such as push_back, emplace_back, insert or resize, invalidates everything into the vector if it causes a reallocation. So does reserve when it grows the block.
    • Without a reallocation, adding at the end still invalidates end(), the iterator for the position just past the last element, because that position has moved.
    • insert and erase shift the elements at and after their position, so references and iterators to those elements, and end(), are invalidated even without a reallocation.
    • pop_back invalidates references to the last element and end(); clear invalidates all of them.

    So push_back doesn’t move anything while the size stays within the capacity. After a reserve, a reference taken early stays valid:

    #include <print>
    #include <vector>
    
    std::vector<int> v;
    v.reserve(4);
    v.push_back(1);
    int& first = v[0];
    v.push_back(2);
    v.push_back(3); // size 3 of capacity 4: nothing moves
    first = 10;
    std::println("{}", v);

    Output

    [10, 2, 3]

    This is easy to break later, by adding one more push_back. Keeping an index and writing v[i] is safer.

    A grid: a vector of vectors or one flat vector

    A grid whose size you only know when the program runs, like an image or a matrix, can be a vector of rows, each its own vector. Or it can be one flat vector in row-major order, where the element at (row, column) is at index row * cols + column:

    #include <cstddef>
    #include <print>
    #include <vector>
    
    std::size_t rows = 2;
    std::size_t cols = 3;
    std::vector<std::vector<int>> nested(rows, std::vector<int>(cols, 0));
    nested[1][2] = 60;
    std::vector<int> flat(rows * cols, 0);
    flat[1 * cols + 2] = 60;
    std::println("{}", nested);
    std::println("{}", flat);

    Output

    [[0, 0, 0], [0, 0, 60]]
    [0, 0, 0, 0, 0, 60]

    Both hold the same six numbers, but not in the same way. nested owns a heap block of two std::vector<int> objects, 24 bytes each here, and each of those owns a separate heap block of three ints. That’s three heap blocks, and the rows can be anywhere in memory. flat owns one block of six ints, side by side:

    The heap blocks behind a 2 × 3 grid of ints
    The heap blocks behind a 2 × 3 grid of ints: each row is one value; each cell's width is its size in bytes.
    Value01234567891011121314151617181920212223242526272829303132333435363738394041424344454647Size
    nested: block of rowsnested[0]: data, size, capacity24 bytes · pointernested[1]: data, size, capacity24 bytes · pointer48 bytes
    nested: row 0's block04 bytes04 bytes04 bytes12 bytes
    nested: row 1's block04 bytes04 bytes604 bytes12 bytes
    flat: one block04 bytes04 bytes04 bytes04 bytes04 bytes604 bytes24 bytes

    nested needs three heap blocks: one with two 24-byte vector objects, each holding a pointer, a size and a capacity, and two separate blocks of three 4-byte ints, one per row. flat needs one heap block of six 4-byte ints, row 0 followed by row 1.

    The flat vector needs one allocation instead of one per row, reads straight through memory without jumping between blocks, and passes to a function as a single std::span<const int>. Prefer it for images, matrices and model weights. A vector of vectors earns its place when the rows have different lengths, like reads of different sizes.

    PerformanceRows in one block are faster to scan

    The processor loads memory in small chunks, so reading elements that sit next to each other is much faster than jumping between blocks. Module 9 measures this; for now, keep data that’s read together stored together.

    std::vector<bool> is different

    std::vector<bool> is a special case. To save memory, the standard lets it store each bool as a single bit, and GCC’s library does, 8 to a byte. Reading and writing elements works as usual:

    #include <print>
    #include <vector>
    
    std::vector<bool> seen(5, false);
    seen[3] = true;
    bool copy = seen[3];
    std::println("{} {}", copy, seen);

    Output

    true [false, false, false, true, false]

    But a single bit has no address of its own, so seen[3] can’t give back a real bool&. It gives back a proxy, a small object that knows which bit it stands for. That’s why a std::vector<bool> has no data(), and why bool& can’t bind to one of its elements (see Common pitfalls). When you need ordinary elements, use std::vector<char> or std::vector<std::uint8_t> and store 0 and 1.

    Which one should I use?

    WhatWhenWhyHow
    push_backYou already have the element.It copies or moves the finished value in.names.push_back(name);
    emplace_backYou have the arguments to create an element.It builds the element in place, with no temporary.reads.emplace_back(5, 'N');
    reserve(n)You know, or can estimate, how many elements you’ll add.One allocation instead of one per doubling.v.reserve(count);
    std::erase_ifRemoving every element that passes a test.One pass over the vector, and no positions to manage.std::erase_if(v, is_low);
    One flat vectorA grid with rows of the same length: images, matrices.One block, read straight through, passed as one span.v[row * cols + column]
    Vector of vectorsRows with different lengths.Each row grows on its own.std::vector<std::vector<int>>

    Rule of thumb: make std::vector your default container. reserve when you know the count, add at the end rather than the middle, and store grids flat.

    Under the hood

    A std::vector<T> is 24 bytes with GCC’s library: pointers to the start of its block, the end of its elements and the end of the block. A reallocation allocates the new block, moves every element into it and frees the old one, so it costs time in proportion to the size. Because the capacity grows by a factor each time (doubling, with GCC’s library), a vector filled with push_back moves each element only once or twice on average, however big it gets. Module 4 shows how the vector decides between moving and copying each element.

    The block only grows on its own. When a vector has shrunk for good, shrink_to_fit() asks for a block that fits the elements. The standard lets the library ignore the request; GCC’s library honors it:

    #include <print>
    #include <vector>
    
    std::vector<int> v(1000, 1);
    v.resize(10);
    std::println("{} {}", v.size(), v.capacity());
    v.shrink_to_fit();
    std::println("{} {}", v.size(), v.capacity());

    Output

    10 1000
    10 10

    shrink_to_fit is itself a reallocation, so it invalidates references into the vector like any other.

    Common pitfalls

    Writing into space made by reserve

    reserve gives a vector room, but its size stays 0, so there’s no element 0 to write to. Writing to v[0] anyway is undefined behavior. GCC’s standard library checks [] in builds without optimization, like this one, so here the program stops with a failed assertion. An optimized build won’t check, and the write lands in memory the vector doesn’t consider used (Undefined behavior has more):

    #include <print>
    #include <vector>
    
    std::vector<int> counts;
    counts.reserve(4);
    counts[0] = 12;
    std::println("{}", counts.size());

    This fails when it runs

    /usr/include/c++/15/bits/stl_vector.h:1263: constexpr std::vector< <template-parameter-1-1>, <template-parameter-1-2> >::reference std::vector< <template-parameter-1-1>, <template-parameter-1-2> >::operator[](size_type) [with _Tp = int; _Alloc = std::allocator<int>; reference = int&; size_type = long unsigned int]: Assertion '__n < this->size()' failed.

    Use resize(4) when you want four elements to write to, or keep reserve and add elements with push_back.

    A bool& to an element of std::vector<bool>

    The elements of a std::vector<bool> are bits, so there’s no bool for a reference to bind to:

    #include <vector>
    
    std::vector<bool> seen(5, false);
    bool& first = seen[0];
    first = true;

    The compiler rejects this

    main.cpp: In function ‘int main()’:
    main.cpp:4:21: error: cannot bind non-const lvalue reference of type ‘bool&’ to an rvalue of type ‘bool’
        4 | bool& first = seen[0];
          |               ~~~~~~^
    In file included from /usr/include/c++/15/vector:69,
                     from main.cpp:1:
    /usr/include/c++/15/bits/stl_bvector.h:105:5: note:   after user-defined conversion: ‘constexpr std::_Bit_reference::operator bool() const’
          | operator bool() const _GLIBCXX_NOEXCEPT
          | ^~~~~~~~

    Write through the element directly, seen[0] = true;, or use a std::vector<char> if you need references or a pointer from data().

    Try it yourself

    Try it yourself

    flatten turns a vector of rows into one flat vector in row-major order. It works, but the vector grows step by step and ends with room for 16 values when it holds 9. Count the values first and reserve exactly that many, so the result is allocated once and its capacity is 9.

    #include <print>
    #include <vector>
    
    std::vector<int> flatten(const std::vector<std::vector<int>>& rows) {
        std::vector<int> flat;
        for (const std::vector<int>& row : rows) {
            for (int value : row) {
                flat.push_back(value);
            }
        }
        return flat;
    }
    
    int main() {
        std::vector<std::vector<int>> rows = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
        std::vector<int> flat = flatten(rows);
        std::println("{} (capacity {})", flat, flat.capacity());
    }

    Expected output

    [1, 2, 3, 4, 5, 6, 7, 8, 9] (capacity 9)
    Show a hint

    Loop over the rows once first and add up row.size() to get the total. Call flat.reserve(total) before the loop that copies the values.

    Show a solution
    #include <cstddef>
    #include <print>
    #include <vector>
    
    std::vector<int> flatten(const std::vector<std::vector<int>>& rows) {
        std::size_t total = 0;
        for (const std::vector<int>& row : rows) {
            total += row.size();
        }
        std::vector<int> flat;
        flat.reserve(total);
        for (const std::vector<int>& row : rows) {
            for (int value : row) {
                flat.push_back(value);
            }
        }
        return flat;
    }
    
    int main() {
        std::vector<std::vector<int>> rows = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
        std::vector<int> flat = flatten(rows);
        std::println("{} (capacity {})", flat, flat.capacity());
    }

    Without reserve, the vector reallocates at 1, 2, 4, 8 and 16 elements, and ends with room for 16. Counting first and calling reserve(9) gets one block of exactly 9, and push_back never has to move anything. Returning the vector hands its block to the caller, so the capacity survives the return.

    Saved in this browser only.