---
title: "The Standard Library: Containers, Iterators and Algorithms"
book: "University Computer Science — Year 2"
subject: computer-science
language: en
chapter: 5
exercises: 12
source: https://one-course.com/books/computer-science/4/en/chapter/5-the-standard-library-containers-iterators-and-algorithms
license: CC-BY-NC-SA-4.0
credit: "One Computer Science Book, One Course (one-course.com)"
---

# Chapter 5 — The Standard Library: Containers, Iterators and Algorithms

The town library wants to know which words come back most often in the titles of its 80 books. Last year that meant a hash table written by hand. The C++ standard library has one, and a balanced search tree, and a sort; the whole count is the loop below, and its heart is the line `count[word]++`.

```cpp
inline std::map<std::string, int> count_words(std::istream &in)
{
    std::map<std::string, int> count;                   // a balanced search tree: kept sorted
    std::string line, word;
    std::getline(in, line);                             // skip the header
    while (std::getline(in, line)) {
        std::istringstream title(title_of(line));
        while (title >> word) {
            std::transform(word.begin(), word.end(), word.begin(),
                [](unsigned char c) { return std::tolower(c); });
            count[word]++;                              // a missing key starts at 0
        }
    }
    return count;
}
```

***Listing 5.1.** Counting words with a `std::map` code/bachelor-2/05-cpp-standard-library/listings/words.hpp*

```
$ g++ -std=c++20 -O2 -Wall -Wextra word_count.cpp -o word_count
$ head -3 books.csv
book_id,title,author,year,genre,pages
1,The Silent Code,Fatou Dalewell,2002,mystery,65
2,The Paper Forest,Zoe Stoneton,1996,sport,133
$ ./word_count < books.csv
262 words, 33 different
the      72
a        12
by       8
code     8
comet    8
forest   8
hidden   8
paper    8
```

***Output 5.1.** The 262 words of the titles, and the most frequent.*

`count[word]` finds the word in a search tree and, if it is missing, inserts it with the value 0; `by_frequency` copies the pairs into a vector and sorts it by count. No allocation, no rebalancing, no hashing was written. This chapter is about knowing what the library did for us, and what it costs.

**You already know.**

Book 3 built the structures this library packages: the dynamic array with its amortised constant append, the linked list, the hash table with its load factor, the balanced search trees, among them the red-black tree, and the binary heap; it also used an *iterator*, an object that designates a position in a collection and moves to the next one. [Chapter 4](https://one-course.com/books/computer-science/4/en/chapter/4-templates-and-generic-programming#ch-b2-cpp-templates): every [container](#def-b2-cpp-standard-library-container) and algorithm below is a [template](https://one-course.com/books/computer-science/4/en/chapter/4-templates-and-generic-programming#def-b2-cpp-templates-template).

## 5.1 Sequence containers

**Definition 5.1 (Container).**

A *container* is a [class template](https://one-course.com/books/computer-science/4/en/chapter/4-templates-and-generic-programming#def-b2-cpp-templates-template) of the standard library that owns a collection of elements of one type, and manages their memory. A *sequence container* keeps the elements in the order the program puts them: `std::array`, `std::vector`, `std::deque`, `std::list`. An *associative container* keeps them sorted by a key, in a balanced search tree: `std::set`, `std::map`. An *unordered container* places them by the hash of their key, in a hash table: `std::unordered_set`, `std::unordered_map`.

The four sequence [containers](#def-b2-cpp-standard-library-container) are four structures of Book 3. `std::array<T, N>` is a C array of fixed size wrapped in a class; `std::vector<T>` the dynamic array; `std::list<T>` the doubly linked list; `std::deque<T>` (double-ended queue) a table of pointers to fixed-size blocks, which grows at both ends without moving its elements. The program below gives each of them the same four integers and measures two things: the size of the object itself, and the distance between the first two elements in memory.

```cpp
template <class C> long gap(const C &c)            // bytes between the first two elements
{
    auto first = c.begin(), second = std::next(c.begin());
    return reinterpret_cast<const char *>(&*second) - reinterpret_cast<const char *>(&*first);
}

int main()
{
    std::array<int, 4> a{1, 2, 3, 4};
    std::vector<int> v{1, 2, 3, 4};
    std::deque<int> d{1, 2, 3, 4};
    std::list<int> l{1, 2, 3, 4};
    std::printf("%-6s %7s %16s\n", "", "sizeof", "1st to 2nd");
    std::printf("%-6s %7zu %16ld\n", "array", sizeof a, gap(a));
    std::printf("%-6s %7zu %16ld\n", "vector", sizeof v, gap(v));
    std::printf("%-6s %7zu %16ld\n", "deque", sizeof d, gap(d));
    std::printf("%-6s %7zu %16ld\n", "list", sizeof l, gap(l));
    d.push_front(0);                                // constant time: deque and list only
    l.push_front(0);
    v.insert(v.begin(), 0);                         // allowed, but moves every element
    std::printf("front %d %d %d, size %zu %zu %zu\n", d.front(), l.front(), v.front(),
        d.size(), l.size(),
                v.size());
    return 0;
}
```

***Listing 5.2.** Four sequence [containers](#def-b2-cpp-standard-library-container) side by side code/bachelor-2/05-cpp-standard-library/listings/containers.cpp*

```
$ g++ -std=c++20 -O2 -Wall -Wextra -o containers containers.cpp && ./containers
        sizeof       1st to 2nd
array       16                4
vector      24                4
deque       80                4
list        24               32
front 0 0 0, size 5 5 5
```

***Output 5.2.** The array holds its elements inside the object; the others hold pointers.*

The `array` object is its 16 bytes of elements. A `vector` is three pointers, 24 bytes, whatever its size, and its elements are side by side on the heap, 4 bytes apart. A `list` is two pointers and a count, and each element lives in a node of its own, with a pointer to the next node and one to the previous: 4 bytes of data in a 32-byte block of the allocator, the nodes here allocated one after the other. The `deque`’s 80 bytes hold the table and the positions of both ends; its elements are contiguous inside each block.

## 5.2 Associative and unordered containers

A `std::map<K, V>` stores pairs of a key and a value, sorted by key; it is the dictionary of Book 3 built on a balanced search tree. A `std::unordered_map<K, V>` offers the same operations on a hash table. Below, both receive eight street names of the town, in the same order.

```cpp
    const char *names[] = {"Mill Row", "Bridge Road", "Station Row", "Castle Way",
                           "River Lane", "Garden Lane", "Orchard Way", "Church Lane"};
    std::map<std::string, int> tree;
    std::unordered_map<std::string, int> table;
    for (int i = 0; i < 8; i++) {
        tree[names[i]] = i + 1;                     // the street's number in the list
        table[names[i]] = i + 1;
    }
    int k = 0;
    for (const auto &[name, n] : tree)              // in increasing order of the key
        std::printf("%s%s(%d)", k++ % 4 ? " " : k > 1 ? "\n     " : "map: ", name.c_str(), n);
    k = 0;
    for (const auto &[name, n] : table)             // in an order set by the hashes
        std::printf("%s%s(%d)", k++ % 4 ? " " : k > 1 ? "\n     " : "\nunordered_map:\n     ",
            name.c_str(), n);
    std::printf("\n%zu elements, %zu buckets, load factor %.2f, max %.1f\n", table.size(),
                table.bucket_count(), table.load_factor(), table.max_load_factor());
    for (std::size_t b = 0; b < table.bucket_count(); b++) {
        std::printf("bucket %2zu:", b);
        for (auto it = table.begin(b); it != table.end(b); ++it)
            std::printf(" %s", it->first.c_str());
        std::printf("\n");
    }
    return 0;
```

***Listing 5.3.** The same eight keys in a tree and in a hash table code/bachelor-2/05-cpp-standard-library/listings/buckets.cpp*

```
$ g++ -std=c++20 -O2 -Wall -Wextra -o buckets buckets.cpp && ./buckets
map: Bridge Road(2) Castle Way(4) Church Lane(8) Garden Lane(6)
     Mill Row(1) Orchard Way(7) River Lane(5) Station Row(3)
unordered_map:
     Church Lane(8) River Lane(5) Castle Way(4) Station Row(3)
     Orchard Way(7) Garden Lane(6) Bridge Road(2) Mill Row(1)
8 elements, 13 buckets, load factor 0.62, max 1.0
bucket  0:
bucket  1:
bucket  2: River Lane
bucket  3:
bucket  4:
bucket  5:
bucket  6:
bucket  7:
bucket  8: Mill Row
bucket  9:
bucket 10: Church Lane
bucket 11: Orchard Way Garden Lane Bridge Road
bucket 12: Castle Way Station Row
```

***Output 5.3.** The map visits the keys in alphabetical order, the hash table in its own.*

The standard does not name the tree behind `std::map`: it requires searches, insertions and removals in logarithmic time, and in practice the libraries use a red-black tree. The figure shows the one the eight insertions built, as the library of the compiler used here really stores it.

![The red-black tree of ’s std::map, inserted in the order Mill Row, Bridge Road, Station Row, Castle Way, River Lane, Garden Lane, Orchard Way, Church Lane. No red node has a red child, and the in-order walk, left subtree, node, right subtree, gives the alphabetical order of the output. The shape was read from the library’s own nodes and recomputed by the insertion algorithm of Book 3.](https://one-course.com/images/onecourse/chapters/computer-science-4/b2-cpp-standard-library/fig-0d2ac4849656.svg)

*The red-black tree of [Listing 5.3](#lst-b2-cpp-standard-library-buckets)’s `std::map`, inserted in the order Mill Row, Bridge Road, Station Row, Castle Way, River Lane, Garden Lane, Orchard Way, Church Lane. No red node has a red child, and the in-order walk, left subtree, node, right subtree, gives the alphabetical order of the output. The shape was read from the library’s own nodes and recomputed by the insertion algorithm of Book 3.*

The hash table has 13 buckets for 8 elements, a load factor of $8/13 \approx 0.62$. Its maximum is 1.0: one more element than buckets, and the table allocates more buckets and moves every element to its new bucket, which is a *rehash*. Bucket 11 holds three names and bucket 12 two, while eight buckets are empty: with a good hash function, collisions are the normal case, not an accident. Search, insertion and removal take constant time on average, and linear time in the worst case, when the keys share one bucket.

![The 13 buckets of the unordered_map, from the output of , drawn as one chain per bucket. The library actually threads every element on a single list and keeps, for each bucket, where its stretch of that list begins, which is why the iteration order of the output visits the buckets in no visible order.](https://one-course.com/images/onecourse/chapters/computer-science-4/b2-cpp-standard-library/fig-089744e7f7b0.svg)

*The 13 buckets of the `unordered_map`, from the output of [Listing 5.3](#lst-b2-cpp-standard-library-buckets), drawn as one chain per bucket. The library actually threads every element on a single list and keeps, for each bucket, where its stretch of that list begins, which is why the iteration order of the output visits the buckets in no visible order.*

## 5.3 Iterators

Every [container](#def-b2-cpp-standard-library-container) gives access to its elements by iterators, which the algorithms of the next section take as arguments: an algorithm written for iterators works on every [container](#def-b2-cpp-standard-library-container).

**Definition 5.2 (Iterator range).**

An *iterator range* is a pair of iterators `first` and `last` of one collection, designating the elements from `first` up to, but not including, `last`: the half-open range $[\texttt{first}, \texttt{last})$. It is empty when `first == last`. `c.begin()` designates the first element of a [container](#def-b2-cpp-standard-library-container) `c` and `c.end()` the position just after the last one, which may be compared with but not read.

Half-open ranges make empty ranges natural and lengths a subtraction, $\texttt{last} - \texttt{first}$, and split well: $[a, m)$ and $[m, b)$ cover $[a, b)$ with no overlap. Not every iterator can do everything a pointer can. A list iterator moves one node at a time and cannot jump by 1000; a map iterator walks the tree in order.

**Definition 5.3 (Iterator category).**

The *iterator categories* are nested sets of operations. An *input* iterator can be read and advanced once, in one pass. A *forward* iterator can be copied and its range traversed several times. A *bidirectional* iterator can also move back (`--it`). A *random-access* iterator can also jump (`it + k`), subtract and compare in constant time. A *contiguous* iterator designates elements adjacent in memory. Each category has a C++20 concept, such as `std::random_access_iterator`.

![The iterator categories, each below the one it refines: a random-access iterator is also a bidirectional one, and so on. An algorithm states the weakest category it needs; std::sort needs random access, so a std::list cannot be given to it and has a sort member of its own.](https://one-course.com/images/onecourse/chapters/computer-science-4/b2-cpp-standard-library/fig-1692944e27c1.svg)

*The [iterator categories](#def-b2-cpp-standard-library-category), each below the one it refines: a random-access iterator is also a bidirectional one, and so on. An algorithm states the weakest category it needs; `std::sort` needs random access, so a `std::list` cannot be given to it and has a `sort` member of its own.*

An iterator holds a pointer into the [container](#def-b2-cpp-standard-library-container)’s memory, and some operations move that memory.

**Definition 5.4 (Iterator invalidation).**

An operation on a [container](#def-b2-cpp-standard-library-container) *invalidates* an iterator, a pointer or a reference to its elements when, after the operation, using it is undefined behaviour. The standard states, for each operation of each [container](#def-b2-cpp-standard-library-container), which ones it invalidates.

For a `vector`, an insertion that exceeds the capacity reallocates and [invalidates](#def-b2-cpp-standard-library-invalidation) everything; one that does not [invalidates](#def-b2-cpp-standard-library-invalidation) the positions from the insertion point on. For a `list` or a `map`, an insertion [invalidates](#def-b2-cpp-standard-library-invalidation) nothing and an erasure only the erased element’s iterators, since no other node moves. For an `unordered_map`, an insertion that causes a rehash [invalidates](#def-b2-cpp-standard-library-invalidation) every iterator, but no pointer or reference to an element, because the nodes do not move: only the bucket table is rebuilt. The program below breaks the `vector` rule.

```cpp
    std::vector<int> due{3, 8, 12, 20};             // days until due; full: capacity 4
    for (int d : due) {                            // the loop holds an iterator into the block
        std::printf("due in %d days\n", d);
        if (d > 10)
            due.push_back(d + 21);                  // renew the loan: the block may move
    }
```

***Listing 5.4.** Renewing the loans due in more than ten days, in the loop that reads them code/bachelor-2/05-cpp-standard-library/listings/invalidation.cpp*

```
$ ./invalidation
due in 3 days
due in 8 days
due in 12 days
=================================================================
==1000==ERROR: AddressSanitizer: heap-use-after-free on address 0x50200000001c at pc 0x555555555781 bp 0x7fffffffeb40 sp 0x7fffffffeb30
READ of size 4 at 0x50200000001c thread T0
    #0 0x555555555780 in main ~/session/invalidation.cpp:9
0x50200000001c is located 12 bytes inside of 16-byte region [0x502000000010,0x502000000020)
freed by thread T0 here:
    #8 0x55555555581d in main ~/session/invalidation.cpp:12
SUMMARY: AddressSanitizer: heap-use-after-free ~/session/invalidation.cpp:9 in main
```

***Output 5.4.** A read of freed memory, staged: the block was freed by the `push_back`. Some lines are left out.*

The range-`for` keeps an iterator `it` and the end iterator, both pointing into the vector’s first block. At 12 days, `push_back` finds the vector full, allocates a block twice as large, moves the four elements and frees the old block; the loop then advances `it`, still in the old block, and reads freed memory. Without the sanitizer the program would print garbage or nothing, depending on what reused the block. The fixes: collect the renewals in a second vector and append them after the loop, or loop on an index, rereading `due[i]` each time.

## 5.4 Generic algorithms and lambda expressions

**Definition 5.5 (Generic algorithm).**

A *generic algorithm* of the standard library is a [function template](https://one-course.com/books/computer-science/4/en/chapter/4-templates-and-generic-programming#def-b2-cpp-templates-template), declared in `<algorithm>` or `<numeric>`, that works on an [iterator range](#def-b2-cpp-standard-library-iterator) rather than on a [container](#def-b2-cpp-standard-library-container), and requires of its iterators a category: `std::find` needs input iterators, `std::sort` random-access ones. Algorithms never add or remove elements of the [container](#def-b2-cpp-standard-library-container): they only read, write or reorder through the iterators.

Most algorithms take an operation as an argument: what *long* means for `count_if`, what *before* means for `sort`. The operation is usually written in place.

**Definition 5.6 (Lambda expression, capture).**

A *lambda expression* `[captures](parameters) { body }` creates an unnamed function object, an object of a class generated by the compiler whose `operator()` runs the body. Its *captures* list the local variables of the enclosing function the body uses: `[x]` stores a copy of `x` in the object, `[&x]` a reference to it, `[=]` and `[&]` capture every variable the body uses, by copy or by reference.

```cpp
    std::vector<int> pages{65, 133, 412, 98, 251, 77, 320, 189};
    int limit = 150;                                        // a local variable, captured below
    auto is_long = [limit](int p) { return p > limit; };     // [limit]: a copy of limit
    long n_long = std::count_if(pages.begin(), pages.end(), is_long);
    auto first = std::find_if(pages.begin(), pages.end(), is_long);
    int total = std::accumulate(pages.begin(), pages.end(), 0);
    std::printf("%ld books over %d pages, the first at position %ld; %d pages in all\n",
        n_long, limit,
                first - pages.begin(), total);

    int calls = 0;
    auto counted = [&calls](int a, int b) { calls++; return a < b; };  // by reference
    std::sort(pages.begin(), pages.end(), counted);
    std::printf("sorted:");
    for (int p : pages)
        std::printf(" %d", p);
    std::printf("\n%d comparisons to sort 8 values\n", calls);

    auto it = std::lower_bound(pages.begin(), pages.end(), 200);               // binary search
    std::printf("first book of at least 200 pages: %d, at position %ld\n",
        *it, it - pages.begin());
```

***Listing 5.5.** Counting, finding, summing, sorting and searching code/bachelor-2/05-cpp-standard-library/listings/lambdas.cpp*

```
$ g++ -std=c++20 -O2 -Wall -Wextra -o lambdas lambdas.cpp && ./lambdas
4 books over 150 pages, the first at position 2; 1545 pages in all
sorted: 65 77 98 133 189 251 320 412
25 comparisons to sort 8 values
first book of at least 200 pages: 251, at position 5
```

***Output 5.5.** 25 comparisons of the sort counted through a captured reference.*

The comparison counter needs a reference capture: a copy would count in the lambda object’s own variable, and the sort copies its comparator, so `calls` would stay 0. `std::lower_bound` searches a sorted range by halving it.

**Proposition 5.7 (Comparisons of a binary search).**

On a sorted range of $n \geq 1$ elements, `std::lower_bound` returns the first position whose element is not less than the key, after at most $\lfloor \log_2 n \rfloor + 1$ comparisons.

**Proof.** The algorithm keeps a range of length $\ell$, initially $n$, that contains the answer’s position or ends just before it. With $h = \lfloor \ell / 2 \rfloor$, it compares the element at offset $h$ with the key: if it is less, the answer lies after it and the range becomes the last $\ell - h - 1$ elements; otherwise the answer is at most this position and the range becomes the first $h$. Both new lengths are at most $\lfloor \ell / 2 \rfloor$. After $k$ comparisons the length is at most $\lfloor n / 2^k \rfloor$, which is 0 as soon as $2^k > n$, that is for $k = \lfloor \log_2 n \rfloor + 1$; a range of length 0 needs no comparison and designates the answer. ∎

C++20 adds *ranges*: the algorithms of `std::ranges` accept a whole [container](#def-b2-cpp-standard-library-container), and *views* compose lazy transformations with `|`, computed only when the loop asks for the next element.

```cpp
    std::vector<int> pages{65, 133, 412, 98, 251, 77, 320, 189};
    namespace views = std::views;
    std::ranges::sort(pages);                                   // no begin() and end() to pass
    auto long_ones = pages | views::filter([](int p) { return p > 150; })
                           | views::transform([](int p) { return p / 10; });  // not run yet
    std::printf("tens of pages of the long books:");
    for (int t : long_ones)                              // computed now, one element at a time
        std::printf(" %d", t);
    std::printf("\nthree largest:");
    for (int p : pages | views::reverse | views::take(3))
        std::printf(" %d", p);
    std::printf("\n%s\n", std::ranges::is_sorted(pages) ? "sorted" : "not sorted");
```

***Listing 5.6.** Views composed with `|` code/bachelor-2/05-cpp-standard-library/listings/ranges.cpp*

```
$ g++ -std=c++20 -O2 -Wall -Wextra -o ranges ranges.cpp && ./ranges
tens of pages of the long books: 18 25 32 41
three largest: 412 320 251
sorted
```

***Output 5.6.** Filtered, transformed, reversed and cut: no intermediate vector was built.*

[Containers](#def-b2-cpp-standard-library-container) and algorithms combine: a map from each member to the vector of that member’s loans groups the town’s 400 loans in one loop, and `count_if` with a lambda counts the late ones (returned after the due date, or still out after it at the end of 2025).

```cpp
    std::vector<Loan> loans = read_loans(argc > 1 ? argv[1] : "loans.csv");
    std::map<int, std::vector<Loan>> by_member;              // member -> that member's loans
    for (const Loan &l : loans)
        by_member[l.member_id].push_back(l);                 // [] creates an empty vector
    std::vector<std::pair<int, int>> counts;                 // (member, number of loans)
    for (const auto &[member, list] : by_member)
        counts.emplace_back(member, int(list.size()));
    std::stable_sort(counts.begin(), counts.end(),
                     [](auto a, auto b) { return a.second > b.second; });
    int today = day_number("2025-12-31");
    std::printf("%zu loans, %zu members who borrowed\n", loans.size(), by_member.size());
    std::printf("member  loans  late\n");
    for (int i = 0; i < 5; i++) {
        const auto &list = by_member.at(counts[i].first);  // at() throws if the key is missing
        auto late_now = [today](const Loan &l) { return is_late(l, today); };
        auto late = std::count_if(list.begin(), list.end(), late_now);
        std::printf("%6d %6d %5ld\n", counts[i].first, counts[i].second, late);
    }
```

***Listing 5.7.** The loans grouped by member code/bachelor-2/05-cpp-standard-library/listings/loans_by_member.cpp*

```
$ g++ -std=c++20 -O2 -Wall -Wextra loans_by_member.cpp -o loans_by_member
$ ./loans_by_member loans.csv
400 loans, 60 members who borrowed
member  loans  late
    55     12     0
    14     11     4
     3     10     1
    12     10     3
    15     10     2
```

***Output 5.7.** The five busiest borrowers.*

## 5.5 Complexity guarantees and measurement

**Definition 5.8 (Complexity guarantee).**

A *complexity guarantee* is a bound that the C++ standard imposes on an operation of the library, counted in operations on the elements (comparisons, copies, hash computations) as a function of the size: *constant*, *logarithmic*, *linear*, possibly *amortised* or *on average*. Every implementation must respect it; it says nothing of the constant factor.

|  | `vector` | `list` | `map` | `unordered_map` |
| --- | --- | --- | --- | --- |
| find a key | $O(n)$; sorted: $O(\log n)$ | $O(n)$ | $O(\log n)$ | $O(1)$ average |
| insert at position $i$ | $O(n - i)$; at the end amort. $O(1)$ | $O(1)$ | — | — |
| insert a key | — | — | $O(\log n)$ | $O(1)$ average |
| erase at position $i$ | $O(n - i)$ | $O(1)$ | amort. $O(1)$ | $O(1)$ average |
| extra memory, each | none | 2 pointers | 3 pointers, colour | 1 pointer |

The guarantees count operations on elements, not time. Two costs they ignore decide many real cases: allocations, one per element for the node-based [containers](#def-b2-cpp-standard-library-container), and the memory cache, which makes reading adjacent bytes far cheaper than following pointers ([Chapter 12](https://one-course.com/books/computer-science/4/en/chapter/12-caches-and-the-memory-hierarchy#ch-b2-caches) measures it). The classic case: insert $n$ random values, each at its place in sorted order, finding the place by walking from the front. Both [containers](#def-b2-cpp-standard-library-container) walk $O(n)$ elements per insertion; the vector then shifts $O(n)$ more, the list links one node, and on paper the list should win.

```cpp
template <class C> double fill_sorted(C &c, const std::vector<int> &values)   // milliseconds
{
    auto t0 = std::chrono::steady_clock::now();
    for (int x : values) {
        auto it = c.begin();
        while (it != c.end() && *it < x)               // linear search in both containers
            ++it;
        c.insert(it, x);                               // vector: shifts; list: links
    }
    auto t1 = std::chrono::steady_clock::now();
    return std::chrono::duration<double, std::milli>(t1 - t0).count();
}
```

***Listing 5.8.** The same work on both [containers](#def-b2-cpp-standard-library-container) code/bachelor-2/05-cpp-standard-library/listings/vector_vs_list.cpp*

```
$ g++ -std=c++20 -O2 -Wall -Wextra -o vector_vs_list vector_vs_list.cpp && ./vector_vs_list
      n   vector ms     list ms   ratio
   1000        0.08        0.32     4.1
   2000        0.28        1.54     5.5
   5000        1.54       18.52    12.0
  10000        6.24       82.61    13.2
  20000       24.50      393.67    16.1
  40000      105.04     2023.74    19.3
```

***Output 5.8.** One run on the author’s laptop; the digits change from run to run.*

![The run of on logarithmic axes. Both curves rise with a slope of about 2 (the list’s a little more), as O(n2) predicts; the list’s curve sits more than ten times higher for large n. Walking a vector reads consecutive bytes, which the processor fetches ahead; walking a list follows a pointer to a node whose address it learns only when the previous load completes.](https://one-course.com/images/onecourse/chapters/computer-science-4/b2-cpp-standard-library/fig-a4aeed2f3210.svg)

*The run of [Output 5.8](#out-b2-cpp-standard-library-vector-vs-list) on logarithmic axes. Both curves rise with a slope of about 2 (the list’s a little more), as $O(n^2)$ predicts; the list’s curve sits more than ten times higher for large $n$. Walking a vector reads consecutive bytes, which the processor fetches ahead; walking a list follows a pointer to a node whose address it learns only when the previous load completes.*

The vector wins at every size, by a factor that grows from 4 to about 20: its shifts are fast copies of contiguous memory, and its walk too, while the list pays a cache miss per node once the list outgrows the cache. The same lesson holds for searching: below, the same keys looked up in a sorted vector with a binary search, in a `map` and in an `unordered_map`.

```
$ g++ -std=c++20 -O2 -Wall -Wextra -o map_vs_unordered map_vs_unordered.cpp && ./map_vs_unordered
        n  sorted vector      map  unordered_map
     1000           30.0     31.0            6.1
    10000           55.1     75.6           11.9
   100000           75.0    196.4           15.3
  1000000          111.1   1026.3           45.3
```

***Output 5.9.** Nanoseconds per lookup, one run on the author’s laptop (the program is `map_vs_unordered.cpp`).*

Both the sorted vector and the map make about $\log_2 n$ comparisons, yet at a million keys the map is about ten times slower: each of its comparisons follows a pointer to a node somewhere on the heap. The hash table makes about one comparison and stays fastest at every size.

**Method 5.9 (Choosing a container).**

1. List the operations the program performs on the collection, with their expected numbers and the sizes.
2. For each candidate [container](#def-b2-cpp-standard-library-container) , add up the costs given by its [complexity guarantees](#def-b2-cpp-standard-library-guarantee) ; discard those whose dominant term is worse.
3. If several remain, or if the sizes are small, write the workload once as a [template](https://one-course.com/books/computer-science/4/en/chapter/4-templates-and-generic-programming#def-b2-cpp-templates-template) over the [container](#def-b2-cpp-standard-library-container) , check that every candidate gives the same results, and measure them at the real sizes.
4. Default to `vector` ; prefer `unordered_map` for lookups by key with no order, `map` when the keys must be visited in order, `list` only when iterators must survive insertions and erasures elsewhere.

**In practice — Which container?.**

Without a measured reason, use `std::vector`. Its guarantees are the weakest for insertion in the middle, and it wins in practice far more often than they suggest, thanks to contiguity. When a measurement is needed, measure at the real sizes: the crossovers move with the processor, the element type and the compiler.

## 5.6 Exercises

**Exercise 5.1 ★.**

Predict the six lines a to f, then check them against the output in the solution. Which line shows that `std::remove` does not remove anything?

```cpp
    std::vector<int> v{4, 1, 4, 2, 4, 3};
    std::printf("a %ld\n", std::count(v.begin(), v.end(), 4));
    std::printf("b %ld\n", std::max_element(v.begin(), v.end()) - v.begin());
    std::vector<double> halves{0.5, 0.5, 0.5, 0.5};
    std::printf("c %g %g\n", double(std::accumulate(halves.begin(), halves.end(), 0)),
                std::accumulate(halves.begin(), halves.end(), 0.0));
    std::vector<int> w{1, 1, 2, 1, 1, 3, 3};
    auto end_unique = std::unique(w.begin(), w.end());
    std::printf("d %ld:", end_unique - w.begin());
    for (auto it = w.begin(); it != end_unique; ++it)
        std::printf(" %d", *it);
    auto end_kept = std::remove(v.begin(), v.end(), 4);
    std::printf("\ne %zu %ld\n", v.size(), end_kept - v.begin());
    v.erase(end_kept, v.end());
    std::printf("f %zu %d\n", v.size(), std::binary_search(v.begin(), v.end(), 3));
    return 0;
```

***Listing 5.9.** Six algorithm calls code/bachelor-2/05-cpp-standard-library/listings/exo_algorithms.cpp*

**Solution of Exercise 5.1.**

```
$ g++ -std=c++20 -O2 -Wall -Wextra -o exo_algorithms exo_algorithms.cpp && ./exo_algorithms
a 3
b 0
c 0 2
d 4: 1 2 1 3
e 6 3
f 3 1
```

***Output 5.13.** The six lines.*

a: three 4s. b: `max_element` returns the *first* largest, at position 0. c: the type of the result is the type of the initial value: with `0`, an `int`, each partial sum $0 + 0.5$ is converted back to `int`, 0; with `0.0` the sum is 2. d: `unique` removes only *consecutive* duplicates, leaving 1 2 1 3 in the first four places. e: `remove` shifts the kept elements to the front and returns the end of them, 3, but the size is still 6: an algorithm cannot change a [container](#def-b2-cpp-standard-library-container)’s size, so the elements after the returned position remain, with unspecified values. f: after `erase` the size is 3 (1 2 3, in order), and `binary_search` finds 3. Line e answers the question.

**Exercise 5.2 ★.**

This loop should remove the even values. Explain the output, then fix it in two ways: with a corrected index loop, and with one call of a C++20 library function.

```cpp
    std::vector<int> v{3, 8, 12, 5, 6, 6, 7, 10};
    for (std::size_t i = 0; i < v.size(); i++)
        if (v[i] % 2 == 0)
            v.erase(v.begin() + long(i));
    for (int x : v)
        std::printf("%d ", x);
    std::printf("\n");
```

***Listing 5.10.** Erasing in a loop code/bachelor-2/05-cpp-standard-library/listings/exo_erase.cpp*

```
$ g++ -std=c++20 -O2 -Wall -Wextra -o exo_erase exo_erase.cpp && ./exo_erase
3 12 5 6 7
```

***Output 5.10.** 12 and one 6 are still there.*

**Solution of Exercise 5.2.**

After erasing at position $i$, the next element slides into position $i$, and `i++` skips it: 12 follows 8 and the second 6 follows the first, so both survive; 10 is still reached, at $i = 5$, and erased. Fix 1: increment `i` only when nothing was erased (`if (even) erase; else i++;`), still $O(n^2)$ moves. Fix 2, linear: `std::erase_if(v, is_even);`, with `is_even` a lambda testing the remainder modulo 2, which is `remove_if` followed by one `erase`.

**Exercise 5.3 ★.**

Write `top_words(count, k)`, which returns the $k$ most frequent words of a map of counts, ties in alphabetical order, with `std::partial_sort`. Compare its cost with sorting the whole vector, for $m$ different words. Check it against `by_frequency` on the town’s titles.

**Solution of Exercise 5.3.**

```cpp
inline std::vector<std::pair<std::string, int>> top_words(
    const std::map<std::string, int> &count, std::size_t k)
{
    std::vector<std::pair<std::string, int>> v(count.begin(), count.end());
    k = std::min(k, v.size());
    // the first k positions receive the k largest, in order; the rest are left in some order
    std::partial_sort(v.begin(), v.begin() + long(k), v.end(),
        [](const auto &a, const auto &b) {
        return a.second != b.second ? a.second > b.second : a.first < b.first;  // ties: a to z
    });
    v.resize(k);
    return v;
}
```

*The $k$ most frequent words code/bachelor-2/05-cpp-standard-library/exercises/top_words.hpp*

`partial_sort` makes about $m \log_2 k$ comparisons (it keeps a heap of the $k$ best), against $m \log_2 m$ for a full sort; for the 33 words of the town and $k = 3$, about 52 against 166. The comparator breaks ties by the word, so the result does not depend on the algorithm’s internal order. `tests/word_count_test.cpp` checks that the first $k$ agree with `by_frequency` on the town’s titles.

**Exercise 5.4 ★.**

A program inserts $n$ distinct keys, one at a time, into an empty `map`, and the same keys into an empty `unordered_map`. Using the guarantees, estimate the number of key comparisons of the first, and the number of hash computations and element moves of the second, rehashes included, assuming the number of buckets about doubles at each rehash.

**Solution of Exercise 5.4.**

The map: the $i$-th insertion searches a tree of $i - 1$ keys, about $\log_2 i$ comparisons, so about $\sum_{i=1}^{n} \log_2 i = \log_2 n! \approx n \log_2 n - 1.44\,n$ comparisons, plus $n$ allocations and rebalancings of constant amortised cost. The hash table: one hash per insertion, $n$ in all, plus the rehashes. If the bucket count doubles each time the load factor passes 1, the rehashes move about $n/2 + n/4 + \dots < n$ elements; the libraries keep the hash in the node or recompute it, at most $n$ more hashes. Total: $O(n)$ on average, against $O(n \log n)$; the measured lookups of [Output 5.9](#out-b2-cpp-standard-library-lookups) show the gap at large $n$.

**Exercise 5.5 ★★.**

Predict the four lines, then check against the output in the solution. Explain each with [Definition 5.6](#def-b2-cpp-standard-library-lambda), including the two sizes of the last line.

```cpp
    int fine = 10;
    auto by_value = [fine] { return fine; };
    auto by_ref = [&fine] { return fine; };
    auto counter = [n = 0]() mutable { return ++n; };   // its own variable, kept between calls
    fine = 25;
    std::printf("%d %d\n", by_value(), by_ref());
    auto copy = counter;
    counter();
    counter();
    std::printf("%d %d\n", counter(), copy());
    auto all = [=] { return fine * 2; };
    auto all_ref = [&] { return fine * 2; };
    fine = 0;
    std::printf("%d %d\n", all(), all_ref());
    std::printf("%zu %zu\n", sizeof by_value, sizeof all_ref);
    return 0;
```

***Listing 5.11.** [Captures](#def-b2-cpp-standard-library-lambda) code/bachelor-2/05-cpp-standard-library/listings/exo_captures.cpp*

**Solution of Exercise 5.5.**

```
$ g++ -std=c++20 -O2 -Wall -Wextra -o exo_captures exo_captures.cpp && ./exo_captures
10 25
3 1
50 0
4 8
```

***Output 5.14.** The four lines.*

Line 1: `by_value` copied `fine` when the lambda was created, 10; `by_ref` reads the variable, now 25. Line 2: `copy` is a copy of the object `counter` taken while its `n` was 0; three calls of `counter` give 3, the first call of `copy` 1. Line 3: `[=]` copied `fine` (25) at creation, 50; `[&]` reads it after it was set to 0. Line 4: the lambda object stores its [captures](#def-b2-cpp-standard-library-lambda): one `int`, 4 bytes, for `by_value`, and one reference, stored as an address, 8 bytes, for `all_ref`.

**Exercise 5.6 ★★.**

`starts_with_street` returns a predicate. The sanitizer reports a read of a stack frame that has returned. Which object is read, and why does it no longer exist? Fix the function. Why did the sanitizer need the option shown, where [Output 5.4](#out-b2-cpp-standard-library-invalidation) did not?

```cpp
std::function<bool(const std::string &)> starts_with_street(const std::string &prefix)
{
    std::string p = prefix + " ";                           // "Orchard " and so on
    return [&p](const std::string &s) { return s.compare(0, p.size(), p) == 0; };
}

int main()
{
    std::setvbuf(stdout, nullptr, _IONBF, 0);
    auto is_orchard = starts_with_street("Orchard");
    std::printf("checking\n");
    std::printf("%d\n", is_orchard("Orchard Lane"));
    return 0;
}
```

***Listing 5.12.** A predicate built by a function code/bachelor-2/05-cpp-standard-library/listings/exo_dangling.cpp*

```
$ ASAN_OPTIONS=detect_stack_use_after_return=1 ./exo_dangling
checking
=================================================================
==1000==ERROR: AddressSanitizer: stack-use-after-return on address 0x7ffff3600048 at pc 0x555555558a27 bp 0x7fffffffe9f0 sp 0x7fffffffe9e0
READ of size 8 at 0x7ffff3600048 thread T0
    #1 0x5555555575f1 in operator() ~/session/exo_dangling.cpp:9
Address 0x7ffff3600048 is located in stack of thread T0 at offset 72 in frame
  This frame has 2 object(s):
    [32, 40) '<unknown>'
    [64, 96) 'p' (line 8) <== Memory access at offset 72 is inside this variable
```

***Output 5.11.** The key lines of the report. Some lines are left out.*

**Solution of Exercise 5.6.**

The lambda [captures](#def-b2-cpp-standard-library-lambda) `p`, a local variable of `starts_with_street`, by reference; the function returns, its frame is gone, and `p` with it. The call in `main` reads `p.size()` through the dangling reference. Fix: capture by value, `[p]`, or move it in, `[p = std::move(p)]`: the string then lives in the lambda object, which `std::function` owns. With the default options, the sanitizer does not watch a returned frame, whose stack memory is soon reused by the next call; the option makes it place frames in separately allocated memory that it marks as dead after the return. A freed heap block, as in [Output 5.4](#out-b2-cpp-standard-library-invalidation), is always watched.

**Exercise 5.7 ★★.**

Group the town’s loans by member, then by the month in which the loan began: a function returning a `std::map<int, std::map<int, int>>` from member to month to number of loans. Why is a map of maps a better choice than an `unordered_map` here? Test that each member’s months add up to that member’s loans.

**Solution of Exercise 5.7.**

```cpp
{
    int z = day + 719468, era = (z >= 0 ? z : z - 146096) / 146097;
    int doe = z - era * 146097;
    int yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365;
    int doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
    int mp = (5 * doy + 2) / 153;
    return mp < 10 ? mp + 3 : mp - 9;
}

// member -> month -> number of loans taken out that month
inline std::map<int, std::map<int, int>> loans_by_member_month(const std::vector<Loan> &loans)
{
    std::map<int, std::map<int, int>> table;
    for (const Loan &l : loans)
        table[l.member_id][month_of(l.out)]++;
    return table;
}
```

*Member, then month code/bachelor-2/05-cpp-standard-library/exercises/by_month.hpp*

`month_of` inverts `day_number`. A `map` visits members and months in increasing order, which is how the table is read and printed; an `unordered_map` would need sorting first, and for 60 members and 12 months the speed of lookups does not matter. `tests/loans_test.cpp` checks that each member’s months add up to the member’s loans, and that the whole adds up to 400.

**Exercise 5.8 ★★.**

(a) Show that $\lfloor \log_2 n \rfloor + 1 = \lceil \log_2 (n + 1) \rceil$ for $n \geq 1$. (b) A search that only compares the key with elements of a sorted range of $n$ elements must be able to return any of $n + 1$ positions. Show, with a decision tree, that it makes at least $\lceil \log_2 (n + 1) \rceil$ comparisons for some key. Conclude that [Proposition 5.7](#prop-b2-cpp-standard-library-lower-bound) is optimal.

**Solution of Exercise 5.8.**

(a) Let $k = \lfloor \log_2 n \rfloor$, so $2^k \leq n < 2^{k+1}$, hence $2^k < n + 1 \leq 2^{k+1}$ and $\lceil \log_2 (n + 1) \rceil = k + 1$. (b) The comparisons a search makes, each with two outcomes, form a binary decision tree whose leaves are the returned positions. Every one of the $n + 1$ positions (0 to $n$) is the right answer for some key, so the tree has at least $n + 1$ leaves; a binary tree of height $h$ has at most $2^h$ leaves, so $2^h \geq n + 1$ and $h \geq \lceil \log_2(n + 1) \rceil$: some key takes that many comparisons. By (a), it is the bound of [Proposition 5.7](#prop-b2-cpp-standard-library-lower-bound), which no comparison-based search can beat.

**Exercise 5.9 ★★.**

Write `LruCache<K, V>`, a cache of fixed capacity with `get` and `put` in constant average time that, when full, evicts the least recently used key. Use a `std::list` of pairs, most recent first, and an `unordered_map` from key to list iterator. Which invalidation rule makes storing list iterators safe? Test it against a slow reference.

**Solution of Exercise 5.9.**

```cpp
template <typename K, typename V>
class LruCache {
public:
    explicit LruCache(std::size_t capacity) : cap_(capacity) {}

    std::optional<V> get(const K &key)              // O(1) on average; makes the key the most recent
    {
        auto it = where_.find(key);
        if (it == where_.end())
            return std::nullopt;
        order_.splice(order_.begin(), order_, it->second);   // move the node to the front, no copy
        return it->second->second;
    }

    void put(const K &key, V value)                 // O(1) on average; evicts the least recent if full
    {
        if (auto it = where_.find(key); it != where_.end()) {
            it->second->second = std::move(value);
            order_.splice(order_.begin(), order_, it->second);
            return;
        }
        if (order_.size() == cap_) {
            where_.erase(order_.back().first);
            order_.pop_back();
        }
        order_.emplace_front(key, std::move(value));
        where_[key] = order_.begin();               // list iterators stay valid when others are erased
    }

    std::size_t size() const { return order_.size(); }

private:
    std::size_t cap_;
    std::list<std::pair<K, V>> order_;              // most recent first
    std::unordered_map<K, typename std::list<std::pair<K, V>>::iterator> where_;
};
```

*An LRU cache code/bachelor-2/05-cpp-standard-library/exercises/lru.hpp*

`splice` moves a node from one place of a list to another without copying it or invalidating any iterator, and erasing the back node [invalidates](#def-b2-cpp-standard-library-invalidation) only that node’s iterators, which the map entry erased with it was the only one to hold. The iterators stored in the map therefore stay valid for as long as their entries exist. With a `vector` instead of the list, every move to the front would shift the others and invalidate their stored positions. `tests/lru_test.cpp` compares 15 000 random operations with a vector kept in recency order.

**Exercise 5.10 ★★★.**

An *interval map* gives a value to every integer key, stored as a `std::map` of the keys where the value changes. Write `IntervalMap<V>` with `operator[]` in $O(\log n)$ and `assign(lo, hi, v)`, which gives the value `v` to the keys $lo \leq k < hi$, keeping the stored form canonical: no two consecutive changes with the same value, and no change to the value before it. Test it against an array on random assignments.

**Solution of Exercise 5.10.**

```cpp
    const V &operator[](int key) const            // O(log n): the last change at or before key
    {
        auto it = changes_.upper_bound(key);
        return it == changes_.begin() ? initial_ : std::prev(it)->second;
    }

    void assign(int lo, int hi, const V &v)         // the keys lo <= k < hi get v
    {
        if (!(lo < hi))
            return;
        V after = (*this)[hi];                      // the value that resumes at hi
        auto first = changes_.lower_bound(lo), last = changes_.lower_bound(hi);
        bool has_hi = last != changes_.end() && last->first == hi;
        changes_.erase(first, last);                // the old changes inside [lo, hi)
        changes_[lo] = v;
        if (!has_hi)
            changes_[hi] = after;
        canonical(lo);
        canonical(hi);
    }

    std::size_t changes() const { return changes_.size(); }

private:
    void canonical(int key)                   // drop a change that repeats the value before it
    {
        auto it = changes_.find(key);
        if (it == changes_.end())
            return;
        const V &before = it == changes_.begin() ? initial_ : std::prev(it)->second;
        if (it->second == before)
            changes_.erase(it);
    }

    V initial_;
    std::map<int, V> changes_;                      // key -> value from this key on
};
```

*An interval map on `std::map` code/bachelor-2/05-cpp-standard-library/exercises/interval_map.hpp*

`upper_bound(key)` is the first change after `key`, so the one before it, if any, is the last change at or before `key`. `assign` saves the value that must resume at `hi`, erases the changes inside $[lo, hi)$, writes the change at `lo` and the change back at `hi`, then removes either of them if it repeats the value before it. It costs $O(\log n)$ plus the number of erased changes, each of which was inserted once. The test checks every key from $-10$ to 49 and the number of stored changes after each of 3000 random assignments.

**Exercise 5.11 ★★★.**

The program below prints, at each `push_back` that moved the elements, the number of elements and the new capacity. (a) For $n$ `push_back`s from empty, give the number of reallocations as a function of $n$, and the total number of element moves. (b) For which values of $i$ does the $i$-th `push_back` invalidate every iterator? (c) Give a call that makes the loop of [Listing 5.4](#lst-b2-cpp-standard-library-invalidation) correct without changing the loop, and say why it is fragile.

```cpp
    std::vector<int> v;
    const int *block = v.data();
    for (int i = 1; i <= 1000; i++) {
        v.push_back(i);
        if (v.data() != block) {                      // a new block: every iterator is invalid
            std::printf("%d:%zu ", i, v.capacity());
            block = v.data();
        }
    }
    std::printf("\n");
    return 0;
```

***Listing 5.13.** Watching the block move code/bachelor-2/05-cpp-standard-library/listings/exo_capacity.cpp*

```
$ g++ -std=c++20 -O2 -Wall -Wextra -o exo_capacity exo_capacity.cpp && ./exo_capacity
1:1 2:2 3:4 5:8 9:16 17:32 33:64 65:128 129:256 257:512 513:1024
```

***Output 5.12.** The reallocations of 1000 `push_back`s.*

**Solution of Exercise 5.11.**

(a) The printed points are 1, 2, 3, 5, 9, …, 513: the capacity doubles, starting at 1. For $n \geq 1$ `push_back`s there are $1 + \lceil \log_2 n \rceil$ reallocations (11 for $n = 1000$), and the moves add up to $1 + 2 + 4 + \dots + 2^{\lceil \log_2 n \rceil - 1} < 2n$. (b) Exactly when $i = 1$ or $i - 1$ is a power of two: the $i$-th call finds $i - 1$ elements in a full block. (c) `due.reserve(8);` before the loop: no `push_back` reallocates, and the end iterator held by the range-`for` still marks four elements, so the loop reads 3, 8, 12 and 20 and stops. It is fragile: one more renewal than reserved and the bug returns, silently.

**Exercise 5.12 ★★★.**

The library keeps a waiting list: a reservation adds a member’s number, and serving removes the smallest number. After $w$ members have joined, 200 000 serve-then-add pairs follow. Write the workload once, as a [template](https://one-course.com/books/computer-science/4/en/chapter/4-templates-and-generic-programming#def-b2-cpp-templates-template) over a queue type with `add`, `serve` and `empty`, and three queue types: a heap (`std::priority_queue`), a `std::multiset` and a vector kept sorted. Test that all three serve the same members in the same order. Then measure them for $w$ from 100 to 100 000, and choose with [Method 5.9](#met-b2-cpp-standard-library-choose).

**Solution of Exercise 5.12.**

```cpp
// ops: a value >= 0 adds that waiting member's number; -1 serves (pops) the smallest
struct HeapQueue {
    std::priority_queue<int, std::vector<int>, std::greater<int>> q;
    void add(int x) { q.push(x); }
    int serve() { int x = q.top(); q.pop(); return x; }
    bool empty() const { return q.empty(); }
};
struct SetQueue {
    std::multiset<int> s;                           // a balanced tree: duplicates allowed
    void add(int x) { s.insert(x); }
    int serve() { int x = *s.begin(); s.erase(s.begin()); return x; }
    bool empty() const { return s.empty(); }
};
struct SortedVectorQueue {
    std::vector<int> v;                // kept in decreasing order: the smallest is at the back
    void add(int x) {
        v.insert(std::lower_bound(v.begin(), v.end(), x, std::greater<int>()), x); }
    int serve() { int x = v.back(); v.pop_back(); return x; }
    bool empty() const { return v.empty(); }
};

template <class Q> std::vector<int> run(const std::vector<int> &ops)  // the values served
{
    Q q;
    std::vector<int> served;
    for (int op : ops)
        if (op >= 0)
            q.add(op);
        else if (!q.empty())
            served.push_back(q.serve());
    return served;
}
```

*One workload, three queues code/bachelor-2/05-cpp-standard-library/exercises/workload.hpp*

```
$ g++ -std=c++20 -O2 -Wall -Wextra -o exo_workload exo_workload.cpp && ./exo_workload
 waiting  heap ms   set ms  sorted vec ms
     100      2.2      3.8            1.1
    1000      3.8      4.2            1.6
   10000      5.1      8.1            7.2
  100000     11.9     38.1          440.9
```

***Output 5.15.** One run on the author’s laptop (`exo_workload.cpp`).*

By the guarantees, the heap and the multiset take $O(\log w)$ per operation and the sorted vector $O(w)$ per insertion (the smallest is at the back, so serving is $O(1)$). The measurement agrees for large $w$: at 100 000 waiting, the vector is about forty times slower than the heap. For a few hundred waiting, the sorted vector is the fastest, and the multiset is slower than the heap at every size (a node allocation per insertion). Choice: the heap, which is never far from the best; the sorted vector only if the list is known to stay short. The test in `tests/exercises_test.cpp` checks the order of service, not the times.

## 5.7 Problem: The town’s loan desk

**Problem 5.1.**

Weekend problem — The town’s loan desk

The loan desk answers four kinds of questions on the 400 loans of `loans.csv`: what is due on a given day, who borrowed what, which loans are late, and how fast all this stays as the library grows. The `Loan` structure and `read_loans` are those of `loans.hpp`, used by [Listing 5.7](#lst-b2-cpp-standard-library-loans).

**Part I — A sorted vector.**

1. Sort the loans by due date, then by loan number, with `std::sort` and a lambda.
2. With `std::lower_bound` and `std::upper_bound` , find the loans due on a given day $d$ . What does `std::equal_range` return?
3. How many comparisons does each search make, by [Proposition 5.7](#prop-b2-cpp-standard-library-lower-bound) , for 400 loans?
4. Write the loans due in a week $[d, d + 7)$ as an [iterator range](#def-b2-cpp-standard-library-iterator) . Why is a half-open range natural here?
5. A new loan arrives. Where does it go, and what does inserting it cost?
6. After that insertion, which iterators into the vector are still valid?

**Part II — Maps.**

7. Build a `std::map<int, std::vector<Loan>>` from member to loans. Why does `by_member[id]` need no check that the key exists?
8. Why does `const` code have to use `at` or `find` instead of `operator[]` ?
9. Replace the map by an `unordered_map` . What changes in the output of [Listing 5.7](#lst-b2-cpp-standard-library-loans) , and what does not?
10. Build a map from book to the number of times it was borrowed, and find the most borrowed book with `std::max_element` .
11. Erase from the map every member with a single loan, in one loop. Write the loop so that no erased iterator is used.
12. A program keeps a pointer to the vector of member 55 in the map, then inserts 100 new members. Is the pointer still valid? And with an `unordered_map` ?

**Part III — Late loans.**

13. Count the late loans at the end of 2025 with `std::count_if` and the predicate `is_late` .
14. Move the late loans to the front of a copy of the vector with `std::partition` , and say what is known of the order afterwards.
15. Keep only the loans still out, with one call of `std::erase_if` .
16. With a view, list the numbers of the first ten late loans without copying the vector.
17. The fine is 10 cents per day late. Sum the fines with `std::transform_reduce` , or with `std::accumulate` and a lambda. Why must the initial value be written `0L` or `0.0` , not `0` , for the second?
18. Write a test that compares the count of question 13 with a loop written by hand.

**Part IV — The crossover.**

19. A sorted vector and a map both answer lookups in about $\log_2 n$ comparisons. Which one pays more per insertion, by the guarantees?
20. The program `crossover.cpp` inserts $n$ random keys and then looks each one up, in a sorted vector and in a map; the output is in the solution. Predict, before reading it, which wins at $n = 1000$ and at $n = 128\,000$ .
21. Explain the measured costs at $n = 1000$ : what does the vector do per insertion, and why is it cheap?
22. Explain the growth of the vector’s cost per key from $n = 16\,000$ on.
23. Why does the map’s cost per key grow too, though slowly?
24. State the result of the problem: the crossover size at which a sorted vector stops beating a map, on the laptop, and the reason it lies there.

**Solution of Problem 5.1.**

**1.** `sort_by_due` in `exercises/loan_desk.hpp`: compare `due`, then `id`.

**2.** `lower_bound(d)` is the first loan due on or after $d$, `upper_bound(d)` the first due after $d$; between them, the loans due on $d$. `equal_range` returns both as a pair, in one call. The comparator must compare a loan with a day in both orders, as `DueBefore` does.

**3.** At most $\lfloor \log_2 400 \rfloor + 1 = 9$ each.

**4.** `due_between(sorted, d, d + 7)`: from `lower_bound(d)` to `lower_bound(d + 7)`. Consecutive weeks $[d, d + 7)$ and $[d + 7, d + 14)$ then share no loan and miss none. The test compares every such range with a count by hand.

**5.** At `upper_bound` of its due date, found in 9 comparisons, but the insertion shifts every later loan: up to 400 moves.

**6.** If the vector had spare capacity, the iterators before the insertion point; otherwise none.

**7.** `operator[]` inserts the key with an empty vector when it is missing, which is what grouping needs.

**8.** `operator[]` may insert, so it does not exist on a `const` map. `at` throws if the key is missing; `find` returns `end()`.

**9.** The counts are the same; the ties of `stable_sort` come out in a different order, since the pairs are now built in the hash table’s order instead of by increasing member number.

**10.** `++borrowed[l.book_id]` for each loan, then `max_element` with a lambda comparing the counts: book 45, borrowed 10 times.

**11.** Loop with `auto it = m.begin(); it != m.end();` and no increment in the header; in the body, `it = m.erase(it);` if the member has one loan, `++it;` otherwise. `erase` returns the iterator after the erased one, so the erased one is never incremented. Three members are removed. In C++20, `std::erase_if(m, pred)` does the same.

**12.** Yes for the map: insertions never move nodes. Yes for the `unordered_map` too: a rehash [invalidates](#def-b2-cpp-standard-library-invalidation) iterators, but pointers and references to the elements survive.

**13.** 109, as in [Chapter 3](https://one-course.com/books/computer-science/4/en/chapter/3-inheritance-and-polymorphism#ch-b2-cpp-polymorphism).

**14.** The late loans come first and `partition` returns the boundary; the order within each part is unspecified. `stable_partition` keeps it, at a higher cost.

**15.** `std::erase_if(v, [](const Loan &l) { return l.returned >= 0; });` keeps the 22 loans still out.

**16.** `loans | views::filter(late) | views::take(10)`, then `views::transform` with a lambda returning `l.id`, with `late` a lambda capturing the day.

**17.** `fines_cents` in `loan_desk.hpp`: 52 850 cents, 528.50. `accumulate` returns the type of its initial value: with `0`, each sum would be computed in `int`, which would suffice here but overflow for a large library, and amounts in `double` would be truncated.

**18.** `tests/loans_test.cpp` counts with a plain loop and compares with `late_count`, and does the same for the fines.

**19.** The vector: $O(n)$ moves per insertion, against $O(\log n)$ for the map.

**20.**

```
$ g++ -std=c++20 -O2 -Wall -Wextra -o crossover crossover.cpp && ./crossover
      n  sorted vector      map
   1000           90.0    114.8
   2000          101.3    135.4
   4000          122.1    140.6
   8000          136.9    142.9
  16000          290.5    212.7
  32000          413.0    184.3
  63998          893.6    223.1
 127997         1797.3    283.4
```

***Output 5.16.** One run on the author’s laptop.*

**21.** At $n = 1000$, an insertion moves on average 500 integers, 2 KB of contiguous memory, which the processor copies at many bytes per cycle; the binary search reads a 4 KB array that stays in the fastest cache. The map allocates a node for each key and follows about ten pointers per search.

**22.** Above about 10 000 keys, the average shift exceeds 20 KB per insertion and grows linearly with $n$: the cost per key doubles when $n$ doubles, as $O(n)$ per insertion predicts.

**23.** Its $\log_2 n$ steps grow slowly, but its nodes no longer fit in the caches, and each step becomes a cache miss.

**24.** *The crossover size at which a sorted vector stops beating a map, on the laptop*: in the printed run, between 8000 and 16 000 keys, about $10^4$; below it the vector is faster per key (by about 20 % at 1000), above it the map is, by a factor that doubles with $n$. It lies where the linear cost of shifting, cheap per element because the memory is contiguous, overtakes the logarithmic cost of the map, high per step because each step follows a pointer.
