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 10 – Standard containers

std::map, std::set and custom comparators

Keep keys sorted with std::map and std::set, answer range queries with lower_bound and upper_bound, and write comparators that are strict weak orderings.

  • Intermediate
  • 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

  • Store sorted keys with std::map and std::set
  • Answer range queries with lower_bound and upper_bound
  • Write comparators that are valid strict weak orderings
  • Find keys by std::string_view without building a std::string
  • Move elements between maps with extract and merge

Before you start

What you’ll learn · Before you start

What you will learn

  • Store sorted keys with std::map and std::set
  • Answer range queries with lower_bound and upper_bound
  • Write comparators that are valid strict weak orderings
  • Find keys by std::string_view without building a std::string
  • Move elements between maps with extract and merge

Before you start

On this page

Asking a word-count map about “zebra” with counts["zebra"] == 0 added the key, and the map grew from 6 to 7 keys. std::map stores key-value pairs sorted by key, and std::set stores keys alone, sorted. Both find, insert and erase a key in O(log n), and both keep their elements in order all the time, so you can walk them from the smallest key to the largest and ask range questions: every key between two values, the first key after a given one, the nearest key below it. Use them when you need that order; when you only look keys up, a hash table is faster, as the first lesson of this module measured.

The order comes from a comparator, std::less by default, and a custom comparator must be a strict weak ordering: The rules a comparator of the ordered containers and of std::sort must follow: comp(a, a) is false, comp is transitive, and keys that neither go before the other form groups of equivalent keys. a < b qualifies; a <= b does not.: one that never says a key comes before itself. Below you count words, query a timetable by ranges, break a set with the most common comparator bug, and move nodes between maps.

A map counts in one line, and its subscript inserts missing keys

word_counts.cpp C++ · word_counts.cpp
// Counting words with std::map: the keys come out in sorted order, and operator[] adds a key that is missing.
#include <map>
#include <print>
#include <sstream>
#include <stdexcept>
#include <string>

int main() {
    std::istringstream text("the cat saw the dog and the dog saw a cat");
    std::map<std::string, int> counts;
    for (std::string word; text >> word;) ++counts[word];  // a new word starts at int{}, which is 0
    std::println("{}", counts);
    std::println("{} distinct words", counts.size());

    // Looking with operator[] inserts what it does not find.
    if (counts["zebra"] == 0) std::println("no zebra, but now there are {} keys", counts.size());

    // find, contains and count only look.
    std::println("contains(\"lion\"): {}, count(\"cat\"): {}", counts.contains("lion"), counts.count("cat"));
    if (auto it = counts.find("dog"); it != counts.end()) std::println("dog appears {} times", it->second);
    std::println("still {} keys", counts.size());

    // at() reads without inserting and throws when the key is missing.
    try {
        std::println("{}", counts.at("lion"));
    } catch (const std::out_of_range&) {
        std::println("at(\"lion\") threw std::out_of_range");
    }
}
Built and run with both compilers Python · word_counts_session.py
from session import run

# word_counts.cpp built and run with both compilers and their standard libraries.
run("""
clang++ -std=c++23 -Wall -Wextra word_counts.cpp -o word_counts
./word_counts
g++-16 -std=c++23 -Wall -Wextra word_counts.cpp -o word_counts-gcc
./word_counts-gcc
""")

Output

$ clang++ -std=c++23 -Wall -Wextra word_counts.cpp -o word_counts
$ ./word_counts
{"a": 1, "and": 1, "cat": 2, "dog": 2, "saw": 2, "the": 3}
6 distinct words
no zebra, but now there are 7 keys
contains("lion"): false, count("cat"): 1
dog appears 2 times
still 7 keys
at("lion") threw std::out_of_range
$ g++-16 -std=c++23 -Wall -Wextra word_counts.cpp -o word_counts-gcc
$ ./word_counts-gcc
{"a": 1, "and": 1, "cat": 2, "dog": 2, "saw": 2, "the": 3}
6 distinct words
no zebra, but now there are 7 keys
contains("lion"): false, count("cat"): 1
dog appears 2 times
still 7 keys
at("lion") threw std::out_of_range

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

Step through the program’s six lookups in order, and watch which of them change the map:

Interactive · stage by stage Six ways to ask a map about a key Step through the program's lookups in order. Each stage is one line of word_counts.cpp; its sub-label is what the line found, and what it did to the map.
Six ways to ask a map about a key, step 6 of 6. Showing ++counts[word], counts["zebra"] == 0, contains("lion"), count("cat"), find("dog"), at("lion"). In focus: at("lion").++counts[word]11 words become 6 keyscounts["zebra"] == 0adds zebra: 7 keyscontains("lion")false, adds nothingcount("cat")1: a map holds 0 or 1find("dog")an iterator to dog: 2at("lion")throws std::out_of_range

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

Every step as text
  1. Counting. ++counts[word] runs once per word of the sentence. For a word seen before it adds one to its count; for a new word, operator[] first inserts it with the value int{}, 0. The map printed its six keys in alphabetical order.
  2. A test that inserts. counts["zebra"] == 0 is meant as a question, but operator[] cannot return a reference to a value that does not exist, so it inserts "zebra" with 0 first. The test is true, and the map has grown from 6 to 7 keys.
  3. Asking without inserting. contains("lion") returns false and changes nothing. contains, added in C++20, is the plain way to ask whether a key is there.
  4. Counting one key. count("cat") returns 1. In a map or a set every key is there once or not at all, so count is 0 or 1; in a multimap it counts every element with that key.
  5. An iterator to the element. find("dog") returns an iterator to the element, and the program read its count, 2, through it. For a missing key it returns end(), which must be checked before the iterator is used. The map still has 7 keys.
  6. Reading or throwing. at("lion") returns a reference to an existing value, and for a missing key throws std::out_of_range, which the program caught. Like find and contains, it never inserts.

  • ++counts[word] is the idiom for counting. operator[] returns a reference to the value stored for the key, and when the key is missing it first inserts the key with a value-initialised value, 0 for an int.
  • The map printed its keys in alphabetical order without being asked: iteration always follows the comparator.
  • The flip side of operator[]: just testing counts["zebra"] == 0 inserted "zebra", and the map grew from 6 to 7 keys. operator[] also cannot be used on a const map, and it needs a value type that can be default-constructed.
  • find returns an iterator, end() when the key is missing; contains (C++20) returns a bool; count returns 0 or 1 for a map. None of them inserts anything.
  • at returns a reference to an existing value and throws std::out_of_range for a missing key.

The elements of a std::map<K, V> are std::pair<const K, V>. The key is const so that nobody can change it in place and break the order; changing a key means removing the element and inserting it again, which the section on extract and merge below does without a copy. For inserting, insert and try_emplace leave an existing value alone and report whether they inserted, while insert_or_assign (C++17) overwrites it.

A std::set<K> is the same tree without values: insert, contains, erase and the range functions below, and its elements are const too. std::multimap and std::multiset allow several elements with equivalent keys, kept in the order they were inserted; count then counts all of them, and equal_range returns them as one range.

Testing a key with operator[]

if (counts[word]) reads like a question, but it inserts every missing word with the value 0, so the map grows by one key for every word it was asked about. Ask with counts.contains(word), or find compared with end(), and keep operator[] for inserting and updating.

Checkpoint

Check: Lookups that insert, and lookups that only look

  1. Question 1 of 2 counts is a std::map<std::string, int> without the key "zebra". What does counts["zebra"] do?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: It inserts the key with the value 0 and returns a reference to that value

    operator[] always returns a reference to a value, so for a missing key it first inserts one, value-initialised: 0 for an int. Use find or contains to look without inserting, and at() to read and throw when the key is missing.

  2. Question 2 of 2 m already maps "pens" to 40. Which call changes the value to 50?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: m.insert_or_assign("pens", 50)

    insert and try_emplace leave an existing value alone and report whether they inserted; insert_or_assign overwrites it. m["pens"] = 50 would work too, by inserting first when the key is missing.

Two bounds turn the order of keys into range queries

Order makes questions possible that a hash table cannot answer without sorting. This timetable maps departure times, in minutes after midnight, to bus routes:

timetable.cpp C++ · timetable.cpp
// Range questions on a std::map: a bus timetable keyed by departure time, in minutes after midnight.
#include <format>
#include <iterator>
#include <map>
#include <print>
#include <string>

std::string hhmm(int minutes) { return std::format("{:02}:{:02}", minutes / 60, minutes % 60); }

int main() {
    std::map<int, std::string> departures{
        {6 * 60 + 40, "route 4"},  {8 * 60 + 5, "route 9"},  {9 * 60, "route 4"},   {9 * 60 + 35, "route 12"},
        {10 * 60 + 20, "route 9"}, {11 * 60, "route 4"},     {12 * 60 + 15, "route 12"},
    };

    // Every departure from 09:00 to 11:00, both included: [lower_bound(09:00), upper_bound(11:00)).
    auto first = departures.lower_bound(9 * 60);   // the first key that is not less than 09:00
    auto last = departures.upper_bound(11 * 60);   // the first key that is greater than 11:00
    std::print("09:00 to 11:00:");
    for (auto it = first; it != last; ++it) std::print("  {} {}", hhmm(it->first), it->second);
    std::println("");

    // The next departure at or after 10:00, and the last one before 10:00.
    auto next = departures.lower_bound(10 * 60);
    std::println("next at or after 10:00: {} {}", hhmm(next->first), next->second);
    if (next != departures.begin()) {
        auto before = std::prev(next);
        std::println("last before 10:00: {} {}", hhmm(before->first), before->second);
    }

    // No departure after 12:15: upper_bound returns end(), which must not be dereferenced.
    auto late = departures.upper_bound(12 * 60 + 15);
    std::println("anything after 12:15? {}", late == departures.end() ? "no" : hhmm(late->first));

    // equal_range gives both bounds for one key: a key that is present, then one that is not.
    auto [from, to] = departures.equal_range(9 * 60 + 35);
    auto [gap_from, gap_to] = departures.equal_range(9 * 60 + 36);
    std::println("09:35 matches {} departure; 09:36 matches {}, and both its bounds point to {}", std::distance(from, to),
                 std::distance(gap_from, gap_to), hhmm(gap_from->first));
}
Range questions on a timetable Python · timetable_session.py
from session import run

# timetable.cpp built and run with both compilers and their standard libraries.
run("""
clang++ -std=c++23 -Wall -Wextra timetable.cpp -o timetable
./timetable
g++-16 -std=c++23 -Wall -Wextra timetable.cpp -o timetable-gcc
./timetable-gcc
""")

Output

$ clang++ -std=c++23 -Wall -Wextra timetable.cpp -o timetable
$ ./timetable
09:00 to 11:00:  09:00 route 4  09:35 route 12  10:20 route 9  11:00 route 4
next at or after 10:00: 10:20 route 9
last before 10:00: 09:35 route 12
anything after 12:15? no
09:35 matches 1 departure; 09:36 matches 0, and both its bounds point to 10:20
$ g++-16 -std=c++23 -Wall -Wextra timetable.cpp -o timetable-gcc
$ ./timetable-gcc
09:00 to 11:00:  09:00 route 4  09:35 route 12  10:20 route 9  11:00 route 4
next at or after 10:00: 10:20 route 9
last before 10:00: 09:35 route 12
anything after 12:15? no
09:35 matches 1 departure; 09:36 matches 0, and both its bounds point to 10:20

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

Each function walks down the tree once, in O(log n):

  • lower_bound(k) returns the first element whose key is not less than k: k itself when it is there, otherwise the next key above it.
  • upper_bound(k) returns the first element whose key is greater than k.
  • equal_range(k) returns both. For the missing 09:36, the range was empty, and both iterators pointed to 10:20, where 09:36 would be inserted.
Keys 06:40 to 12:15 in order; lower_bound(09:00) is 09:00, where the range starts, and upper_bound(11:00) is 12:15.the map's keys, in order06:40before the range08:05before the range09:00lower_bound(09:00):the range starts here09:35in the range10:20in the range11:00in the range12:15upper_bound(11:00):the range stops before it

The two bounds of the range query from 09:00 to 11:00

Text description of the diagram

The diagram is a table of the seven departure times of the timetable example, the map's keys, in order from top to bottom, each with its role in the query "every departure from 09:00 to 11:00".

  1. 06:40 and 08:05 come before the range.
  2. 09:00 is what lower_bound(09:00) returns, the first key that is not less than 09:00: the range starts there.
  3. 09:35, 10:20 and 11:00 are in the range.
  4. 12:15 is what upper_bound(11:00) returns, the first key that is greater than 11:00: the range stops just before it.

So the range from lower_bound(09:00) up to, but not including, upper_bound(11:00) holds 09:00, 09:35, 10:20 and 11:00. Had there been no key greater than 11:00, upper_bound would have returned end().

In minutes after midnight the seven departures are 400 (06:40), 485, 540, 575, 620, 660 and 735 (12:15). Step through a search for 600, that is 10:00, in a search tree of those seven keys, and note each turn it takes:

Interactive · step through it Searching the timetable's keys for 600 minutes, 10:00 Each comparison picks one subtree and rules out the other.
Binary search tree, keys in order: 400 485 540 575 620 660 735; root 575.400485540575620660735
  • being compared or looked at
  • visited or ruled out

Pseudo-code

  1. curr ← root
  2. while curr ≠ null:
  3. if x = curr.key: return curr
  4. if x < curr.key: curr ← curr.left
  5. else: curr ← curr.right
  6. return "not found"

Search the tree for 600. Each comparison sends the search into one subtree and rules the other out.

When it finishes: 600 not found.

Comparisons 0

The search went right at 575, then left at 660 and left at 620, and found no child: 600 is not a key. A bound walks the same path and remembers the last key at which it turned left. For lower_bound(600) that is 620, the 10:20 departure, which is the “next at or after 10:00” that the program printed. The figure inserts the seven times middle first, so its tree is balanced from the start; std::map’s red-black tree rebalances itself as keys arrive, so its shape may differ, but every lookup walks one path from the root in the same way.

The two bounds form a half-open range: A range written [first, last) that includes its first position and stops before its last, like a loop from marks to marks + 5. It holds last - first elements, and it is empty when first == last. More in “Pointer arithmetic, arrays and std::span”, like begin() and end(): [lower_bound(a), upper_bound(b)) holds every key from a to b, both included, and [lower_bound(a), lower_bound(b)) stops before b. For “the last key before k”, step back from lower_bound(k) with std::prev, but only after checking that it is not begin(). Every bound may also be end(), as upper_bound(12:15) was, and dereferencing end() is undefined behaviour.

Key idea

lower_bound(k) is the first key not less than k, upper_bound(k) the first key greater than k; together they give half-open ranges, and either one may be end().

Checkpoint

Check: lower_bound, upper_bound and ranges

  1. Question 1 of 2 Which call returns an iterator to the first key that is greater than k?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: m.upper_bound(k)

    upper_bound(k) skips every key equal to k; lower_bound(k) stops at the first key that is not less than k, which is k itself when it is present. equal_range(k) returns the pair of lower_bound(k) and upper_bound(k).

  2. Question 2 of 2 The timetable holds departures from 06:40 to 12:15. How does the program find the last departure before 10:00?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: It takes lower_bound(10:00) and steps back once with std::prev, after checking that it is not begin()

    lower_bound(10:00) returns 10:20, the first key that is not less than 10:00. The element before it, 09:35, is the last departure before 10:00, as the program printed. When lower_bound returns begin(), there is no earlier departure, and stepping back would be undefined behaviour.

A comparator must never say a key comes before itself

A map or set never asks whether two keys are equal. It only asks its comparator comp(a, b): does a go before b? Two keys are equivalent keys: Two keys a and b are equivalent for a comparator comp when neither comp(a, b) nor comp(b, a) is true. Ordered containers keep one element per group of equivalent keys and find a key by equivalence, never by ==. when neither goes before the other, and the container keeps one element per equivalent key. The C++ standard requires comp to induce a strict weak ordering, which comes down to three rules:

  1. Irreflexive: comp(a, a) is false. Nothing goes before itself.
  2. Transitive: if a goes before b and b before c, then a goes before c.
  3. Equivalence is transitive: if a is equivalent to b and b to c, then a is equivalent to c.

< on integers and strings, > for a descending order, and comparing a single field, such as a.age < b.age, all qualify; < on floating-point values qualifies only while no NaN is among them. Comparing by age makes two people of the same age equivalent, so a std::set ordered that way keeps only one person per age; that is legal, and sometimes exactly what you want, but often a surprise. <= breaks rule 1. Step through the questions a set asks when the same key arrives twice, with each comparator:

Interactive · step by step How a set decides that 3 is already there Step through the questions a set asks its comparator, with a < b on the left and a <= b on the right.
How a set decides that 3 is already there, step 5 of 5. Showing with a < b, with a <= b, comp(3, 3) is false, comp(3, 3) is true, insert(3) again, insert(3) again, count(3), count(3). In focus: insert(3) again, count(3).with a < ba strict weak orderingwith a <= bthe bug of less_equal.cppcomp(3, 3) is falsewhichever 3 comes firstcomp(3, 3) is true3 goes before 3insert(3) againequivalent: not addedinsert(3) againnever equivalent: addedcount(3)1count(3)0, with three 3s insidesize 5, {1, 2, 3, 3, 3}

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

Every step as text
  1. Two comparators. A set never asks whether two keys are equal. It asks only comp(a, b), does a go before b, and treats two keys as equivalent when neither goes before the other. It keeps one element per equivalent key.
  2. A key against itself. With <, comp(3, 3) is false, whichever 3 is passed first, so two 3s are equivalent. With <=, comp(3, 3) is true: the comparator says that 3 goes before 3, which breaks the first rule of a strict weak ordering.
  3. Inserting a second 3. With <, the set finds an equivalent key and does not add the second 3. With <=, no two 3s are ever equivalent, because each one goes before the other, so every insertion of 3 adds a new node.
  4. Looking 3 up. count(3) asks how many elements are equivalent to 3. With < the answer is 1. With <= nothing is equivalent to 3, not even the 3s in the set, so the answer is 0.
  5. What the program printed. The set built with <= from 3, 1, 3, 2 and 3 printed size 5, elements {1, 2, 3, 3, 3}, count(3) = 0 and contains(3) = false with both libraries. libc++'s debug mode stopped it at an insertion: Comparator does not induce a strict weak ordering.

This is what <= does in a real set and a real sort:

less_equal.cpp C++ · less_equal.cpp
// A comparator that uses <= instead of < breaks the rule every ordered container relies on: it is not a strict
// weak ordering, because it says that a value comes before itself. This set is the result.
#include <print>
#include <set>

struct LessOrEqual {
    bool operator()(int a, int b) const { return a <= b; }  // wrong: must be a < b
};

int main() {
    std::set<int, LessOrEqual> s;
    for (int x : {3, 1, 3, 2, 3}) s.insert(x);
    std::println("size {}, elements {}", s.size(), s);
    std::println("count(3) = {}, contains(3) = {}, find(3) found it: {}", s.count(3), s.contains(3), s.find(3) != s.end());
}
less_equal_sort.cpp C++ · less_equal_sort.cpp
// The same <= comparator given to std::ranges::sort, on 40 equal values and one smaller one.
#include <algorithm>
#include <print>
#include <vector>

int main() {
    std::vector<int> v(40, 7);
    v.push_back(1);
    std::ranges::sort(v, [](int a, int b) { return a <= b; });  // undefined behaviour: not a strict weak ordering
    std::println("sorted {} values, the first is {}", v.size(), v.front());
}
The <= comparator in a set and in a sort, with each library's checks Python · less_equal_session.py
from session import run

# less_equal.cpp with both libraries, then with libc++'s debug hardening mode, which checks the comparator.
# less_equal_sort.cpp with AddressSanitizer and with each library's debug mode; grep and sed keep the key line of
# each report and hide the addresses, which change on every run.
run("""
clang++ -std=c++23 -Wall -Wextra less_equal.cpp -o less_equal && ./less_equal
g++-16 -std=c++23 -Wall -Wextra less_equal.cpp -o less_equal-gcc && ./less_equal-gcc
clang++ -std=c++23 -D_LIBCPP_HARDENING_MODE=_LIBCPP_HARDENING_MODE_DEBUG less_equal.cpp -o less_equal-debug
./less_equal-debug 2>&1 | grep -o "libc++ Hardening assertion.*"
clang++ -std=c++23 -g -fsanitize=address less_equal_sort.cpp -o sort_asan
ASAN_OPTIONS=symbolize=0 ./sort_asan 2>&1 | grep -E "ERROR|of size" | sed -E 's/==[0-9]+==//; s/0x[0-9a-f]+/0x…/g'
clang++ -std=c++23 -D_LIBCPP_HARDENING_MODE=_LIBCPP_HARDENING_MODE_DEBUG less_equal_sort.cpp -o sort_debug
./sort_debug 2>&1 | grep -o "libc++ Hardening assertion.*"
g++-16 -std=c++23 -D_GLIBCXX_DEBUG less_equal_sort.cpp -o sort_debug-gcc
./sort_debug-gcc 2>&1 | grep "Error"
""")

Output

$ clang++ -std=c++23 -Wall -Wextra less_equal.cpp -o less_equal && ./less_equal
size 5, elements {1, 2, 3, 3, 3}
count(3) = 0, contains(3) = false, find(3) found it: false
$ g++-16 -std=c++23 -Wall -Wextra less_equal.cpp -o less_equal-gcc && ./less_equal-gcc
size 5, elements {1, 2, 3, 3, 3}
count(3) = 0, contains(3) = false, find(3) found it: false
$ clang++ -std=c++23 -D_LIBCPP_HARDENING_MODE=_LIBCPP_HARDENING_MODE_DEBUG less_equal.cpp -o less_equal-debug
$ ./less_equal-debug 2>&1 | grep -o "libc++ Hardening assertion.*"
libc++ Hardening assertion __result ? !static_cast<bool>(__comp_(__rhs_, __lhs_)) : true failed: Comparator does not induce a strict weak ordering
$ clang++ -std=c++23 -g -fsanitize=address less_equal_sort.cpp -o sort_asan
$ ASAN_OPTIONS=symbolize=0 ./sort_asan 2>&1 | grep -E "ERROR|of size" | sed -E 's/==[0-9]+==//; s/0x[0-9a-f]+/0x…/g'
ERROR: AddressSanitizer: container-overflow on address 0x… at pc 0x… bp 0x… sp 0x…
READ of size 4 at 0x… thread T0
$ clang++ -std=c++23 -D_LIBCPP_HARDENING_MODE=_LIBCPP_HARDENING_MODE_DEBUG less_equal_sort.cpp -o sort_debug
$ ./sort_debug 2>&1 | grep -o "libc++ Hardening assertion.*"
libc++ Hardening assertion __first != __end failed: Would read out of bounds, does your comparator satisfy the strict-weak ordering requirement?
$ g++-16 -std=c++23 -D_GLIBCXX_DEBUG less_equal_sort.cpp -o sort_debug-gcc
$ ./sort_debug-gcc 2>&1 | grep "Error"
Error: attempt to dereference a past-the-end iterator.

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

  • The set kept three 3s and could not find any of them. Under <=, two 3s are never equivalent, because each one goes before the other, so every insertion added a node. Lookups ask “is there an element equivalent to 3?”, and with this comparator nothing is, so count(3) returned 0. Both libraries produced the same broken set, and neither complained.
  • libc++’s debug mode stopped at the insertion, with “Comparator does not induce a strict weak ordering”. It checks, on the comparisons it happens to make, that comp(a, b) and comp(b, a) are never both true.
  • The sort read memory outside the vector. std::ranges::sort relies on the ordering to stop its inner loops, and with <= a loop over equal values ran past the last element. AddressSanitizer reported a container-overflow: a read beyond the vector’s size, inside its spare capacity. libc++’s debug mode stopped the sort and named the likely cause, a comparator that breaks the ordering rules, while libstdc++’s debug mode reported an attempt to dereference a past-the-end iterator. Without a checker, nothing stops the loop: it goes on reading whatever memory follows the vector, and from then on the program’s behaviour is undefined.

Both debug modes are slow and change how the library behaves, so they belong in test builds. The fix is always the same: compare with <, never <=, and for several fields compare them in order. The tuple lesson’s std::tie(a.marks, a.name) < std::tie(b.marks, b.name) is a strict weak ordering for any number of fields.

A comparator is part of the container’s type: std::set<int, std::greater<>> and std::set<int> are different types. Any type with a const call operator works, and since C++20 a lambda without captures does too: std::set<Student, decltype(by_marks)>.

Checkpoint

Check: Strict weak orderings

  1. Question 1 of 2 Which of these comparators can order a std::set<int>?

    Choose every answer that is right.

    Show the answer: Question 1 of 2

    Answer:

    • std::abs(a) < std::abs(b)
    • a > b
    • a < b

    A strict weak ordering never says that a value comes before itself, and it treats "neither comes first" as an equivalence. a > b sorts from high to low, and comparing absolute values is valid too: -3 and 3 are then equivalent, so the set keeps only the first of them that is inserted. a <= b says that 3 comes before 3, and a != b says that 1 comes before 2 and 2 before 1.

  2. Question 2 of 2 The lesson's set with the <= comparator received 3, 1, 3, 2 and 3. How many elements did it hold afterwards, with both libraries?

    Type a number.

    Show the answer: Question 2 of 2

    Answer: 5 elements

    With <=, two 3s are never equivalent, because each compares before the other, so every insertion added a node: the set held 1, 2, 3, 3, 3. count(3) then returned 0, because no element is equivalent to 3 under this comparator. All of this is undefined behaviour; libc++'s debug mode stopped the program instead.

A transparent comparator looks keys up without building them

With the default comparator std::less<std::string>, a std::map<std::string, int> can only search for a std::string. A key that arrives as a std::string_view or a string literal has to become a temporary std::string first, and a string longer than its built-in buffer (22 characters in libc++, 15 in libstdc++) allocates memory for that. std::less<>, the comparator with no type, can compare a std::string with anything that compares with one, and it says so with a member type named is_transparent. Such a transparent comparator: A comparator that declares a member type named is_transparent, as std::less<> does, so that a map or a set accepts lookups by any type the comparator can compare with its keys, such as a std::string_view in a map of std::string. makes the map’s lookup functions accept other types. Step through one lookup with each comparator:

Interactive · step by step One lookup by std::string_view, two comparators Step through one find of a 31-character key that arrives as a std::string_view, with the default comparator on the left and std::less<> on the right.
One lookup by std::string_view, two comparators, step 5 of 5. Showing a std::string_view key, std::less<std::string>, std::less<>, a temporary std::string, compares the view, plain: 1,000 lookups, transparent: 1,000. In focus: plain: 1,000 lookups, transparent: 1,000.find(std::string(key))find(key)built firsta std::string_view key31 charactersstd::less<std::string>compares strings onlystd::less<>is_transparenta temporary std::string31 characters on the heapcompares the viewwith each std::string keyplain: 1,000 lookups1,000 allocationstransparent: 1,000no allocation

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

Every step as text
  1. A key that is not a string. The key arrives as a std::string_view of 31 characters, for example a slice of a request. The maps hold std::string keys.
  2. The default comparator. With std::less<std::string>, find accepts only a std::string, so the program has to build one from the view before every lookup.
  3. A temporary string. 31 characters do not fit in a std::string's built-in buffer, 22 characters in libc++ and 15 in libstdc++, so every temporary allocates memory on the heap, and frees it after the lookup.
  4. A transparent comparator. std::less<> declares a member type named is_transparent, so the map offers find for any type it can compare with its keys. find(key) takes the view as it is.
  5. The count. The program counted every allocation: 1,000 lookups made 1,000 allocations with std::less<std::string> and none with std::less<>, with both libraries.

This program counts the allocations of 1,000 such lookups:

transparent.cpp C++ · transparent.cpp
// Looking up a std::string key with a std::string_view: with the default comparator, std::less<std::string>, the
// view must first become a std::string, which allocates when the text is too long for the string's own buffer.
// std::less<> compares a std::string with a std::string_view directly. The global operator new below counts every
// allocation the program makes.
#include <cstddef>
#include <cstdlib>
#include <functional>
#include <map>
#include <new>
#include <print>
#include <string>
#include <string_view>

static std::size_t allocations = 0;
void* operator new(std::size_t n) {
    ++allocations;
    if (void* p = std::malloc(n)) return p;
    throw std::bad_alloc{};
}
void operator delete(void* p) noexcept { std::free(p); }
void operator delete(void* p, std::size_t) noexcept { std::free(p); }

template <class Map>
std::size_t allocations_for_lookups(const Map& m, std::string_view key, int times) {
    std::size_t before = allocations;
    int found = 0;
    for (int i = 0; i < times; ++i) {
        if constexpr (requires { m.find(key); }) found += m.find(key) != m.end();  // a heterogeneous lookup
        else found += m.find(std::string(key)) != m.end();                     // build a std::string first
    }
    if (found != times) std::println("missing key!");
    return allocations - before;
}

int main() {
    const std::string_view key = "customer-000123-billing-address";  // 31 characters: too long to fit in place
    std::map<std::string, int> plain{{std::string(key), 1}};
    std::map<std::string, int, std::less<>> transparent{{std::string(key), 1}};

    std::println("1000 lookups, std::less<std::string>: {} allocations", allocations_for_lookups(plain, key, 1000));
    std::println("1000 lookups, std::less<>:            {} allocations", allocations_for_lookups(transparent, key, 1000));
}
Allocations for 1,000 lookups of a 31-character key Python · transparent_session.py
from session import run

# transparent.cpp with -O2, with each compiler and its standard library.
run("""
clang++ -std=c++23 -O2 -Wall -Wextra transparent.cpp -o transparent
./transparent
g++-16 -std=c++23 -O2 -Wall -Wextra transparent.cpp -o transparent-gcc
./transparent-gcc
""")

Output

$ clang++ -std=c++23 -O2 -Wall -Wextra transparent.cpp -o transparent
$ ./transparent
1000 lookups, std::less<std::string>: 1000 allocations
1000 lookups, std::less<>:            0 allocations
$ g++-16 -std=c++23 -O2 -Wall -Wextra transparent.cpp -o transparent-gcc
$ ./transparent-gcc
1000 lookups, std::less<std::string>: 1000 allocations
1000 lookups, std::less<>:            0 allocations

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

A thousand lookups cost a thousand allocations with std::less<std::string> and none with std::less<>, with both libraries. find, count, lower_bound, upper_bound and equal_range accept such keys since C++14 (paper N3657), contains since it was added in C++20, and erase and extract since C++23. Insertion with operator[] or try_emplace still needs a std::string until C++26, which adds those overloads too (paper P2363R5). A transparent comparator is opt-in because it changes which overloads exist: the default keeps existing code behaving as before. Such a lookup by another type is called a heterogeneous lookup: A lookup by a key of another type than the container's own, such as a std::string_view in a map of std::string. Ordered containers allow it when their comparator is transparent; unordered ones when both the hash and the equality test are..

Checkpoint

Check: Lookups by another key type

  1. Question 1 of 2 m is a std::map<std::string, int>, and keys arrive as std::string_view. What makes m.find(sv) compile without building a std::string?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: Declaring the map as std::map<std::string, int, std::less<>>

    std::less<> is transparent, so the map's find, count, contains, lower_bound, upper_bound and equal_range accept any type it can compare with the keys. sv.data() compiles, but converts to a temporary std::string, which allocates for long text, and it is wrong for a view that is not null-terminated.

  2. Question 2 of 2 The map uses std::less<>. Which of these still needs a std::string key in C++23?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: m[key] and m.try_emplace(key, v)

    With a transparent comparator, find, count, lower_bound, upper_bound and equal_range take other key types since C++14, contains since C++20, and erase and extract since C++23. operator[] and try_emplace follow in C++26.

extract and merge move nodes between maps without a copy

Every element of a map lives in a node of its own, and C++17 lets you take a node out and put it back, or into another map, without copying the element or allocating a new node. Step through the program’s calls and watch who owns each node:

Interactive · step by step Nodes moving between maps Step through the calls of the program. The arrows show which map, or which node handle, owns each node; the nodes themselves never move in memory.
Nodes moving between maps, step 5 of 5. Showing Meera's node (key 3), a node handle (empty), the map seats (keys 3, 14, 15, 20, 21), the map waitlist (key 14 only), Asha's node, Dev's node. In focus: Asha's node, Dev's node, the map seats, the map waitlist.in seatsin seatsin waitlistMeera's nodekey 3a node handleemptythe map seatskeys 3, 14, 15, 20, 21the map waitlistkey 14 onlyAsha's nodekey 20Dev's nodekey 14

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

Every step as text
  1. Two maps. seats holds seats 12, 14 and 15, and Meera sits in seat 12; the program keeps a pointer to her string. waitlist holds Dev for seat 14, Asha for 20 and Ravi for 21, each in a node of its own.
  2. extract(12). seats.extract(12) unlinks Meera's node from the tree and returns a node handle that owns it. Nothing is copied or allocated, and seats no longer has key 12.
  3. A new key. Inside a map a key is const, but through the handle it is not: node.key() = 3 moves Meera to seat 3 without touching her string.
  4. insert(std::move(node)). insert links the same node back into seats, at the place key 3 sorts to. The program printed allocations: 0, same string object: true.
  5. merge(waitlist). seats.merge(waitlist) moves every node whose key seats does not have yet: Asha's for 20 and Ravi's for 21. Seat 14 is taken by Arjun, so Dev's node stays in waitlist. allocations: 0 again, and Asha's string was not copied.

nodes.cpp C++ · nodes.cpp
// extract and merge (C++17) move nodes between maps without copying or allocating: a key can change, and elements
// can change maps, while pointers to them stay valid. The global operator new below counts allocations.
#include <cstddef>
#include <cstdlib>
#include <map>
#include <new>
#include <print>
#include <string>

static std::size_t allocations = 0;
void* operator new(std::size_t n) {
    ++allocations;
    if (void* p = std::malloc(n)) return p;
    throw std::bad_alloc{};
}
void operator delete(void* p) noexcept { std::free(p); }
void operator delete(void* p, std::size_t) noexcept { std::free(p); }

int main() {
    std::map<int, std::string> seats{{12, "Meera, travelling with a guide dog"}, {14, "Arjun"}, {15, "Kabir"}};
    const std::string* meera = &seats.at(12);

    // Move Meera from seat 12 to seat 3: the key of a map element is const, so take the node out, change it, put it back.
    std::size_t before = allocations;
    auto node = seats.extract(12);  // a node handle now owns the element; the map no longer has it
    node.key() = 3;
    seats.insert(std::move(node));
    std::size_t made = allocations - before;  // counted before printing, which may allocate
    std::println("{}", seats);
    std::println("allocations: {}, same string object: {}", made, &seats.at(3) == meera);

    // merge moves every node whose key is not in the target yet; the others stay where they were.
    std::map<int, std::string> waitlist{{14, "Dev"}, {20, "Asha"}, {21, "Ravi"}};
    const std::string* asha = &waitlist.at(20);
    before = allocations;
    seats.merge(waitlist);
    made = allocations - before;
    std::println("seats    {}", seats);
    std::println("waitlist {}  (seat 14 was taken)", waitlist);
    std::println("allocations: {}, Asha's string was not copied: {}", made, &seats.at(20) == asha);
}
A key changed and two maps merged, without allocating Python · nodes_session.py
from session import run

# nodes.cpp built and run with both compilers and their standard libraries.
run("""
clang++ -std=c++23 -Wall -Wextra nodes.cpp -o nodes
./nodes
g++-16 -std=c++23 -Wall -Wextra nodes.cpp -o nodes-gcc
./nodes-gcc
""")

Output

$ clang++ -std=c++23 -Wall -Wextra nodes.cpp -o nodes
$ ./nodes
{3: "Meera, travelling with a guide dog", 14: "Arjun", 15: "Kabir"}
allocations: 0, same string object: true
seats    {3: "Meera, travelling with a guide dog", 14: "Arjun", 15: "Kabir", 20: "Asha", 21: "Ravi"}
waitlist {14: "Dev"}  (seat 14 was taken)
allocations: 0, Asha's string was not copied: true
$ g++-16 -std=c++23 -Wall -Wextra nodes.cpp -o nodes-gcc
$ ./nodes-gcc
{3: "Meera, travelling with a guide dog", 14: "Arjun", 15: "Kabir"}
allocations: 0, same string object: true
seats    {3: "Meera, travelling with a guide dog", 14: "Arjun", 15: "Kabir", 20: "Asha", 21: "Ravi"}
waitlist {14: "Dev"}  (seat 14 was taken)
allocations: 0, Asha's string was not copied: true

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

  • extract(12) unlinked the node of seat 12 and returned a node handle: The object that extract returns: it owns one element of a node-based container, such as a map, until the node is inserted into a container of the same kind or the handle is destroyed. Through it, a map's key can be changed. that owns it. Through the handle the key is no longer const, so node.key() = 3 moved Meera to seat 3, and insert linked the same node back in.
  • merge moved every node of the waitlist whose key was free in seats. Seat 14 was already taken, so Dev’s node stayed in the waitlist.
  • Neither step allocated, and pointers to the moved strings still pointed to them: the elements never moved. That matters for large values, and for code that keeps pointers or references to elements.

A map can take nodes from any std::map or std::multimap with the same key, value and allocator types, even one with another comparator. Sets and multisets work the same way, and so do the unordered containers among themselves.

Checkpoint

Check: extract and merge

  1. Question 1 of 2 After auto node = seats.extract(12); on a std::map<int, std::string> that held key 12, what is true?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: The map no longer holds key 12, and node owns the element until it is inserted somewhere or destroyed

    extract unlinks the node and hands it to a node handle, without copying or allocating. node.key() can be changed, which is impossible inside the map, and inserting the handle into a map with the same allocator puts the same node back.

  2. Question 2 of 2 seats holds seat 14, and waitlist holds Dev for seat 14, Asha for 20 and Ravi for 21. Where is Dev after seats.merge(waitlist)?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: Still in waitlist, because seats already had key 14

    merge moved Asha's and Ravi's nodes, whose keys 20 and 21 were free in seats, and left Dev's in waitlist, because seat 14 was taken. The program printed waitlist {14: "Dev"} and allocations: 0.

Practise: book a meeting room

A room’s bookings are half-open intervals of minutes, [start, end), kept in a std::map from start to end. Write Room::book(start, end): it adds the booking and returns true, or returns false and changes nothing when the new booking overlaps an existing one. A booking that starts exactly when another ends does not overlap it.

The starter code and its sample tests

C header · bookings.h

// Starter code for the exercise: the bookings of one meeting room, each a half-open interval [start, end) of minutes
// after midnight, kept in a std::map from start to end.
#pragma once
#include <map>
#include <utility>
#include <vector>

class Room {
public:
    // Books [start, end) and returns true; or returns false, and changes nothing, when it overlaps a booking.
    // A booking that starts exactly when another one ends does not overlap it. start is always less than end.
    bool book(int start, int end) {
        // TODO: look at bookings_.lower_bound(start) and at the booking just before it
        (void)start;
        (void)end;
        return false;
    }

    // Every booking in order of start time, for the tests.
    std::vector<std::pair<int, int>> list() const { return {bookings_.begin(), bookings_.end()}; }

private:
    std::map<int, int> bookings_;  // start -> end
};

C++ · bookings_tests.cpp

// Sample tests for bookings.h. Build: clang++ -std=c++23 -g -fsanitize=address,undefined -Wall -Wextra bookings_tests.cpp -o bookings_tests
#include <print>
#include <random>
#include <utility>
#include <vector>
#include "bookings.h"

int checks = 0;
int failures = 0;

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

// The slow way, easy to get right: compare with every booking.
struct SlowRoom {
    std::vector<std::pair<int, int>> bookings;
    bool book(int start, int end) {
        for (auto [s, e] : bookings)
            if (start < e && s < end) return false;
        bookings.emplace_back(start, end);
        return true;
    }
};

int main() {
    Room room;
    check(room.book(600, 660), "10:00 to 11:00 in an empty room");
    check(room.book(660, 720), "a booking that starts when another ends");
    check(room.book(540, 600), "a booking that ends when another starts");
    check(!room.book(630, 690), "an overlap with two bookings");
    check(!room.book(610, 620), "a booking inside another one");
    check(!room.book(500, 800), "a booking around all the others");
    check(!room.book(600, 660), "the same booking twice");
    check(room.list() == std::vector<std::pair<int, int>>{{540, 600}, {600, 660}, {660, 720}}, "the three bookings, in order");

    // 5,000 random requests over a day, compared with the slow way.
    Room fast;
    SlowRoom slow;
    std::mt19937 random(3);
    bool same = true;
    for (int i = 0; i < 5'000 && same; ++i) {
        int start = int(random() % 1'400);
        int end = start + 1 + int(random() % 40);
        same = fast.book(start, end) == slow.book(start, end);
    }
    check(same, "5,000 random requests get the same answers as the slow way");

    std::println("{} of {} checks passed", checks - failures, checks);
    return failures == 0 ? 0 : 1;
}
The sample tests against the starter code Python · bookings_session.py
from session import run

# The sample tests run against the starter code, before the TODO is done, with the sanitizers switched on.
run("""
clang++ -std=c++23 -g -fsanitize=address,undefined -Wall -Wextra bookings_tests.cpp -o bookings_tests && ./bookings_tests
g++-16 -std=c++23 -g -fsanitize=address,undefined -Wall -Wextra bookings_tests.cpp -o bookings_tests-gcc && ./bookings_tests-gcc
""")

Output

$ clang++ -std=c++23 -g -fsanitize=address,undefined -Wall -Wextra bookings_tests.cpp -o bookings_tests && ./bookings_tests
FAIL 10:00 to 11:00 in an empty room
FAIL a booking that starts when another ends
FAIL a booking that ends when another starts
FAIL the three bookings, in order
FAIL 5,000 random requests get the same answers as the slow way
4 of 9 checks passed
[exit status 1]
$ g++-16 -std=c++23 -g -fsanitize=address,undefined -Wall -Wextra bookings_tests.cpp -o bookings_tests-gcc && ./bookings_tests-gcc
FAIL 10:00 to 11:00 in an empty room
FAIL a booking that starts when another ends
FAIL a booking that ends when another starts
FAIL the three bookings, in order
FAIL 5,000 random requests get the same answers as the slow way
4 of 9 checks passed
[exit status 1]

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

The starter refuses every booking, so it passes only the four checks that expect a refusal. You are done when both compilers print 9 of 9 checks passed. Because the bookings never overlap, only two existing bookings can collide with a new one: the first one that starts at or after start, which lower_bound(start) finds, and the one just before it. Check both in O(log n) instead of looking at every booking; the last test compares your answers with the slow way on 5,000 random requests. emplace_hint(next, start, end) inserts at the position you already found.

Checkpoint

Check: lower_bound, upper_bound and ranges

  1. One question The room's bookings never overlap, and a request asks for [start, end). Which existing bookings can collide with it?

    Choose one answer.

    Show the answer: One question

    Answer: The first one that starts at or after start, and the one just before it

    Two checks in O(log n) are enough: the booking at lower_bound(start) must not start before end, and the booking just before it must end at or before start. A booking that starts exactly when another ends does not overlap it.

When the nine checks pass, test yourself on subscripts, bounds, comparators, transparent lookups and node handles. The practice follows your answers and gives the reason for every option:

Practice that adapts to you

Practise this lesson

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

  1. Question 1 of 15 In which order did the word-counting program print the map's keys?

    Choose one answer.

    Show the answer: Question 1 of 15

    Answer: In alphabetical order, the order of the comparator std::less<std::string>

    Iterating over a std::map visits its keys in the comparator's order, std::less by default, so the counts came out as a, and, cat, dog, saw, the with both libraries.

  2. Question 2 of 15 std::map<std::string, std::string> names; and then names["Asha"] += " Rao";. What does names["Asha"] hold?

    Choose one answer.

    Show the answer: Question 2 of 15

    Answer: " Rao"

    For a missing key, operator[] inserts it with a value-initialised value: 0 for an int, an empty string for a std::string. The += then works on that new value.

  3. Question 3 of 15 A std::multimap<int, std::string> holds three elements with the key 7. What do count(7) and equal_range(7) give?

    Choose one answer.

    Show the answer: Question 3 of 15

    Answer: 3, and a range of the three elements, in the order they were inserted

    std::multimap and std::multiset allow several elements with equivalent keys, kept in the order they were inserted; count counts all of them, and equal_range returns them as one range.

  4. Question 4 of 15 The timetable holds 09:35. What does lower_bound(09:35) return?

    Choose one answer.

    Show the answer: Question 4 of 15

    Answer: An iterator to 09:35 itself

    lower_bound(k) returns k itself when it is present, and otherwise the next key above it. upper_bound(k) always skips k.

  5. Question 5 of 15 Which pair of iterators covers every departure from 09:00 to 11:00, both included?

    Choose one answer.

    Show the answer: Question 5 of 15

    Answer: [lower_bound(09:00), upper_bound(11:00))

    The two bounds form a half-open range: [lower_bound(a), upper_bound(b)) holds every key from a to b, both included. The program printed 09:00, 09:35, 10:20 and 11:00 for this range.

  6. Question 6 of 15 auto late = departures.upper_bound(12:15); and 12:15 is the last departure. What may the program do with late?

    Choose one answer.

    Show the answer: Question 6 of 15

    Answer: Compare it with end(), because it is end(), which must not be dereferenced

    Every bound may be end(), and dereferencing end() is undefined behaviour, so compare it with end() before using it, as the program did.

  7. Question 7 of 15 In the figure's tree of departure times in minutes, a search for 600 went right at 575, then left at 660 and left at 620, and found no child. Which key, in minutes, does lower_bound(600) return?

    Type a number.

    A hint

    lower_bound remembers the last key at which the walk turned left.

    Show the answer: Question 7 of 15

    Answer: 620 minutes

    Each left turn happens at a key that is not less than 600, and the last one, 620, is the smallest such key: 10:20, the next departure at or after 10:00 that the program printed.

  8. Question 8 of 15 Which rule of a strict weak ordering does the comparator a <= b break?

    Choose one answer.

    Show the answer: Question 8 of 15

    Answer: Irreflexivity, that comp(a, a) is false

    A strict weak ordering must never say that a key comes before itself: comp(a, a) must be false. With <=, comp(3, 3) is true, so no 3 is equivalent to any other, and the container breaks.

  9. Question 9 of 15 A std::set<Person, ByAge> compares a.age < b.age. Two people of age 30 are inserted. What does the set hold?

    Choose one answer.

    Show the answer: Question 9 of 15

    Answer: Only the first of them, because people of the same age are equivalent

    Comparing a single field is a strict weak ordering, so the set works, and it keeps one person per age. That is legal and sometimes wanted, but often a surprise; std::multiset, or a comparator over more fields, keeps both.

  10. Question 10 of 15 Students must be ordered by marks, and students with equal marks by name. Which comparator does that as a strict weak ordering?

    Choose one answer.

    Show the answer: Question 10 of 15

    Answer: std::tie(a.marks, a.name) < std::tie(b.marks, b.name)

    std::tie builds tuples of references, and tuples compare lexicographically: the first field that differs decides. That is a strict weak ordering for any number of fields.

  11. Question 11 of 15 What tells a std::map that its comparator can compare keys with other types?

    Choose one answer.

    Show the answer: Question 11 of 15

    Answer: A member type of the comparator named is_transparent

    A comparator says it is transparent with a member type named is_transparent, as std::less<> does. Only then do the map's find, count, contains and bound functions accept other key types.

  12. Question 12 of 15 Why is heterogeneous lookup opt-in, instead of the default for every map?

    Choose one answer.

    Show the answer: Question 12 of 15

    Answer: It changes which overloads exist, so the default keeps existing code behaving as before

    A transparent comparator adds lookup overloads for other types. Making that the default would change which overload existing code calls, so the standard leaves it to a comparator such as std::less<> to opt in.

  13. Question 13 of 15 Why is the key of a std::map element const?

    Choose one answer.

    Show the answer: Question 13 of 15

    Answer: So that nobody can change it in place and break the order of the tree

    The elements of a std::map<K, V> are std::pair<const K, V>. A key changed in place would leave its node in the wrong part of the tree, so the only way to change one is to take the node out, as extract does.

  14. Question 14 of 15 How many allocations did seats.merge(waitlist) make, moving two passengers between the maps?

    Type a number.

    Show the answer: Question 14 of 15

    Answer: 0 allocations

    merge relinks the nodes of the keys that are free in the target, so nothing is allocated and no string is copied: the program printed allocations: 0 and "Asha's string was not copied: true".

  15. Question 15 of 15 A program keeps a pointer to Meera's string, then runs extract(12), changes the key to 3 and inserts the node again. What does the pointer point to?

    Choose one answer.

    Show the answer: Question 15 of 15

    Answer: The same string, now in the element with key 3

    extract and insert move the node itself, so pointers and references to the element follow it through the change of key. That is why node handles suit large values and code that keeps pointers to elements.

Interview questions

Fresher · What is the difference between m[key], m.at(key) and m.find(key) on a std::map?

All three look the key up in O(log n); they differ in what happens when it is missing. m[key] returns a reference to the value, and for a missing key it first inserts the key with a value-initialised value, such as 0 or an empty string, so it changes the map and cannot be used on a const map. m.at(key) returns a reference to an existing value and throws std::out_of_range for a missing key, so it never inserts. m.find(key) returns an iterator to the element, or m.end() for a missing key, and never inserts or throws; check it before dereferencing. Use [] to insert or update, at when a missing key is an error, and find or contains to ask whether the key is there. A common bug is testing if (m[key]), which quietly adds every key it tests.

The usual follow-ups test the two traps in that answer, the const map and the test that inserts. Decide both:

Checkpoint

Interview round: two follow-up questions

  1. Question 1 of 2 Follow-up: a function takes const std::map<std::string, int>& m and reads m["dog"]. What happens?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: It does not compile, because operator[] may insert and so has no const version

    operator[] inserts a missing key, so it needs a non-const map. Reading code that takes a const map uses at() when a missing key is an error, or find and contains when it is not.

  2. Question 2 of 2 Follow-up: a loop calls if (m[name]) … for 10,000 names, of which 9,000 are not in the map of 100 entries. How many entries does the map hold afterwards?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: 9,100, because every name tested with operator[] that was missing was inserted with a value of 0

    if (m[key]) quietly adds every key it tests: here 9,000 new entries with the value 0, each a node of its own. m.contains(name), or find with a check against end(), asks without inserting.

Ordered maps are also the subject of two design questions in this module’s bank, each building on the bounds of this lesson: one side of a limit order book, and the price in effect at a given time:

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

  1. Senior to staff

    Design one side of a limit order book in C++: orders rest at price levels, the best price must be found at once, orders at a level are filled in arrival order, and any order can be cancelled by its id. Which containers do you combine, with what keys and comparators, and what does each operation cost?

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

  2. Fresher to mid

    Price changes are stored in a std::map<std::int64_t, Price> keyed by the time, in milliseconds, at which they take effect. Write the lookup for the price in effect at time t, list its edge cases, and make it fast for a stream of queries whose t only increases.

    Model answer, Pro. First step and follow-ups

Key takeaways

  • std::map and std::set keep their keys sorted: lookups, insertions and erasures take O(log n), and iteration follows the key order.
  • operator[] inserts a missing key; find, contains and count only look, and at throws for a missing key.
  • lower_bound(k) is the first key not less than k and upper_bound(k) the first key greater than k; together they give a half-open range, and either can be end().
  • A comparator must be a strict weak ordering. With <=, the set kept three 3s, found none of them, and the sort read past the end of its vector; libc++’s debug mode named the bug.
  • std::less<> lets lookups take a std::string_view without building a std::string: 1,000 lookups made 1,000 allocations without it and none with it.
  • extract and merge move nodes between maps without copying or allocating, and can change a key.

Terms in this lesson

equivalent keys
Two keys a and b are equivalent for a comparator comp when neither comp(a, b) nor comp(b, a) is true. Ordered containers keep one element per group of equivalent keys and find a key by equivalence, never by ==.
heterogeneous lookup
A lookup by a key of another type than the container's own, such as a std::string_view in a map of std::string. Ordered containers allow it when their comparator is transparent; unordered ones when both the hash and the equality test are.
node handle
The object that extract returns: it owns one element of a node-based container, such as a map, until the node is inserted into a container of the same kind or the handle is destroyed. Through it, a map's key can be changed.
strict weak ordering
The rules a comparator of the ordered containers and of std::sort must follow: comp(a, a) is false, comp is transitive, and keys that neither go before the other form groups of equivalent keys. a < b qualifies; a <= b does not.
transparent comparator
A comparator that declares a member type named is_transparent, as std::less<> does, so that a map or a set accepts lookups by any type the comparator can compare with its keys, such as a std::string_view in a map of std::string.

Corrections

  • The section on comparators now names comparing by age as the comparator that keeps only one person per age.

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.