Skip to content
binshelf/ cpp

Search lessons

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

    Lessons

    On this page

    1. Key terms
    2. In 30 seconds
    3. std::map: values you look up by key
    4. Looking up a key: contains, find and at
    5. [] adds the key if it’s missing
    6. Adding without replacing: insert, emplace and try_emplace
    7. Looping over a map
    8. Keys can’t change
    9. std::unordered_map: a hash table
    10. Keys need a hash
    11. Sets: keys without values
    12. std::flat_map: a sorted map in two vectors
    13. Which one should I use?
    14. Under the hood
    15. Common pitfalls
    16. [] on a const map
    17. Erasing while looping
    18. Try it yourself

    Module 3 · Strings and containers

    3.3Maps and sets

    Look values up by key with std::map and std::unordered_map, keep unique keys with std::set, and learn why reading a map with [] can quietly add entries.

    About 25 minutesBeginner

    On this page
    1. Key terms
    2. In 30 seconds
    3. std::map: values you look up by key
    4. Looking up a key: contains, find and at
    5. [] adds the key if it’s missing
    6. Adding without replacing: insert, emplace and try_emplace
    7. Looping over a map
    8. Keys can’t change
    9. std::unordered_map: a hash table
    10. Keys need a hash
    11. Sets: keys without values
    12. std::flat_map: a sorted map in two vectors
    13. Which one should I use?
    14. Under the hood
    15. Common pitfalls
    16. [] on a const map
    17. Erasing while looping
    18. Try it yourself

    Key terms

    key and value
    A map stores pairs: the key is what you look up by, the value is what you get back. Each key appears at most once.
    std::map<K, V>
    A map that keeps its pairs sorted by key. From <map>.
    std::unordered_map<K, V>
    A map that keeps its pairs in a hash table, in no particular order. Usually faster than std::map. From <unordered_map>.
    m[key]
    Gives the value for key, adding the key with a default value first (0 for numbers, empty for strings) if it's missing.
    std::set<K> and std::unordered_set<K>
    Containers of keys alone, each stored once: sorted, or in a hash table.
    hash table
    An array of buckets. A hash function turns each key into a number, its hash, which picks the key's bucket, so a lookup only checks the few keys in one bucket.
    balanced tree
    Nodes linked so that each has a smaller-key side and a larger-key side, kept about equally deep. std::map is one.
    std::flat_map<K, V>
    A sorted map that stores its keys in one vector and its values in another (C++23). From <flat_map>.

    Often you need to find something by name, not by position: the read count for each sample, or how often each k-mer (a piece of DNA k letters long) appears in a sequence. With a std::vector, you’d search every element each time. A map stores key-value pairs and finds a key quickly. A set stores keys alone, each one once.

    In 30 seconds

    • std::map<K, V> keeps key-value pairs sorted by key. std::unordered_map<K, V> keeps them in a hash table, in no particular order, and is usually faster.
    • Look a key up with contains, find or at. m[key] adds the key with a default value if it’s missing: handy for counting, a bug when you only meant to read.
    • Loop over a map with for (const auto& [key, value] : m).
    • std::set and std::unordered_set hold keys alone, each one once.

    std::map: values you look up by key

    std::map<K, V> (from <map>) maps keys of type K to values of type V. Here the keys are sample names and the values are read counts. m[key] = value adds a new pair, or replaces the value if the key is already there:

    #include <map>
    #include <print>
    #include <string>
    
    std::map<std::string, int> reads = {{"sample_b", 120}, {"sample_a", 95}};
    reads["sample_c"] = 40;  // new key: adds a pair
    reads["sample_a"] = 100; // existing key: replaces its value
    std::println("{} samples", reads.size());
    std::println("{}", reads);

    Output

    3 samples
    {"sample_a": 100, "sample_b": 120, "sample_c": 40}

    Each key appears at most once, and a std::map keeps its pairs sorted by key, whatever order you add them in. It compares keys with <, so strings come out in alphabetical order. std::println prints a map in braces, as key: value.

    Looking up a key: contains, find and at

    There are three ways to ask about a key, depending on what you need back:

    #include <map>
    #include <print>
    #include <string>
    
    std::map<std::string, int> reads = {{"sample_a", 95}, {"sample_b", 120}};
    
    if (reads.contains("sample_a")) {
        std::println("sample_a is here");
    }
    std::println("sample_b: {}", reads.at("sample_b"));
    
    auto it = reads.find("sample_c");
    if (it == reads.end()) {
        std::println("no sample_c");
    }
    auto found = reads.find("sample_a");
    if (found != reads.end()) {
        std::println("{} has {} reads", found->first, found->second);
    }

    Output

    sample_a is here
    sample_b: 120
    no sample_c
    sample_a has 95 reads
    • contains(key) answers yes or no.
    • at(key) returns the value. If the key is missing, it throws std::out_of_range, like .at() on a std::array (Arrays and span shows what that does).
    • find(key) returns an iterator, an object that marks the element’s position. If the key is missing, it returns end(), the position just past the last element, so always compare with end() before you use it. Each element is a std::pair, two values named first and second. -> reaches the element through the iterator, as through a pointer: found->first is the key and found->second is the value.

    Use find when you need the value but the key might be missing: it checks and finds in one search, where contains followed by at searches twice.

    [] adds the key if it’s missing

    m[key] always gives you a value to read or change. If the key isn’t there, it first adds it, with a default value: 0 for numbers, false for bool, an empty string for std::string. Reading a missing key with [] changes the map:

    #include <map>
    #include <print>
    #include <string>
    
    std::map<std::string, int> reads = {{"sample_a", 95}};
    int n = reads["sample_z"]; // not there: adds sample_z with 0
    std::println("{} {}", n, reads.size());
    std::println("{}", reads);

    Output

    0 2
    {"sample_a": 95, "sample_z": 0}

    That same behavior makes counting short. The first time a base appears, [] adds it with 0, and ++ makes it 1:

    #include <map>
    #include <print>
    #include <string>
    
    std::string dna = "GATTACA";
    std::map<char, int> counts;
    for (char base : dna) {
        ++counts[base];
    }
    std::println("{}", counts);

    Output

    {'A': 3, 'C': 1, 'G': 1, 'T': 2}

    Common pitfall[] is for writing, find and at are for reading

    Use [] when adding the key is what you want, as in counting. To read, use find, contains or at: they never change the map.

    Adding without replacing: insert, emplace and try_emplace

    [] replaces an existing value. insert, emplace and try_emplace add a pair only if the key is new, and leave an existing one alone. insert returns two things in a std::pair: an iterator to the element with that key, and a bool that says whether it was added. A structured binding, auto [pos, added], gives the two parts names; optional, variant and tuple covers structured bindings in depth.

    #include <map>
    #include <print>
    #include <string>
    
    std::map<std::string, int> reads = {{"sample_a", 95}};
    
    auto [pos, added] = reads.insert({"sample_a", 7}); // key exists: no change
    std::println("{} {}", added, pos->second);
    
    reads.emplace("sample_b", 120);         // builds the pair from its parts
    reads.try_emplace("sample_c", 40);      // checks the key first
    reads.insert_or_assign("sample_a", 99); // adds or replaces, like []
    reads.erase("sample_b");                // removes the key, if it's there
    std::println("{}", reads);

    Output

    false 95
    {"sample_a": 99, "sample_c": 40}

    emplace builds the pair from the arguments you give it, but it may build it before finding out the key exists, and then throw it away. try_emplace looks for the key first and builds nothing if it’s there. That matters when the value is expensive to build, like a big std::vector, so prefer try_emplace to emplace for maps. insert_or_assign(key, value) does what m[key] = value does, with a name that says so: it adds or replaces.

    Looping over a map

    A range for visits every pair, in key order for a std::map. Each element is a std::pair<const std::string, int>, and const auto& [sample, count] names its two halves without copying them:

    #include <map>
    #include <print>
    #include <string>
    
    std::map<std::string, int> reads = {
        {"sample_b", 120}, {"sample_a", 95}, {"sample_c", 40}};
    for (const auto& [sample, count] : reads) {
        std::println("{}: {}", sample, count);
    }
    for (auto& [sample, count] : reads) {
        count *= 2; // changes the value in the map
    }
    std::println("{}", reads);

    Output

    sample_a: 95
    sample_b: 120
    sample_c: 40
    {"sample_a": 190, "sample_b": 240, "sample_c": 80}

    With auto&, the names refer to the parts of each element in the map, so changing count changes the map. That’s the same rule as auto& in References.

    Keys can’t change

    The key is const even through auto&: changing a key in place would break the map’s order. The compiler stops you:

    #include <map>
    
    std::map<int, int> positions = {{1, 100}, {2, 200}};
    for (auto& [key, value] : positions) {
        key += 10;
    }

    The compiler rejects this

    main.cpp: In function ‘int main()’:
    main.cpp:5:9: error: assignment of read-only reference ‘key’
        5 |     key += 10;
          |     ~~~~^~~~~

    To change a key, erase the old pair and insert a new one.

    std::unordered_map: a hash table

    std::unordered_map<K, V> (from <unordered_map>) has the same operations: [], find, contains, at, insert, try_emplace, erase and the loop. What’s different is how it stores the pairs: in a hash table, not in sorted order. It turns each key into a number, the key’s hash, and the number leads straight to one small group of keys, called a bucket. For most lookups that’s faster than searching a sorted tree; Under the hood shows both.

    #include <print>
    #include <string>
    #include <unordered_map>
    
    std::unordered_map<std::string, int> reads = {{"sample_a", 95},
                                                  {"sample_b", 120}};
    reads["sample_c"] = 40;
    ++reads["sample_a"];
    std::println("{} {} {}", reads.size(), reads.at("sample_a"),
                 reads.contains("sample_z"));

    Output

    3 96 false

    The order you get when you loop over a std::unordered_map isn’t specified. It can change when you add elements, and it differs between standard libraries. Don’t rely on it. When you need the pairs in order, copy them into a std::map: std::map<std::string, int> sorted(reads.begin(), reads.end());, where begin() and end() mark the first element and the position past the last.

    Keys need a hash

    To find a key’s bucket, std::unordered_map needs a hash function for the key type, std::hash<K>. The standard library has one for numbers, characters, strings and pointers, but not for a std::pair. The message is about the hash, even though the code never mentions one:

    #include <unordered_map>
    #include <utility>
    
    std::unordered_map<std::pair<int, int>, double> grid;
    grid[{0, 1}] = 2.5;

    The compiler rejects this

    In file included from /usr/include/c++/15/bits/unordered_map.h:33,
                     from /usr/include/c++/15/unordered_map:43,
                     from main.cpp:1:
    /usr/include/c++/15/bits/hashtable.h: In instantiation of ‘class std::_Hashtable<std::pair<int, int>, std::pair<const std::pair<int, int>, double>, std::allocator<std::pair<const std::pair<int, int>, double> >, std::__detail::_Select1st, std::equal_to<std::pair<int, int> >, std::hash<std::pair<int, int> >, std::__detail::_Mod_range_hashing, std::__detail::_Default_ranged_hash, std::__detail::_Prime_rehash_policy, std::__detail::_Hashtable_traits<true, false, true> >’:
    /usr/include/c++/15/bits/unordered_map.h:115:18:   required from ‘class std::unordered_map<std::pair<int, int>, double>’
          |   _Hashtable _M_h;
          |              ^~~~
    main.cpp:4:49:   required from here
        4 | std::unordered_map<std::pair<int, int>, double> grid;
          |                                                 ^~~~
    /usr/include/c++/15/bits/hashtable.h:210:51: error: static assertion failed: hash function must be copy constructible
          |   static_assert(is_copy_constructible<_Hash>::value,
          |                                               ^~~~~
    /usr/include/c++/15/bits/hashtable.h:210:51: note: ‘std::integral_constant<bool, false>::value’ evaluates to false
    compilation terminated due to -fmax-errors=1.

    “hash function must be copy constructible” means here that std::hash<std::pair<int, int>> doesn’t exist. Use std::map<std::pair<int, int>, double> instead: a std::map needs only <, and pairs have it. Operators and comparisons shows how to give your own types <, so they can be std::map keys too.

    Sets: keys without values

    std::set<K> (from <set>) stores keys alone, sorted, each one once. Adding a key that’s already there does nothing. insert returns the same pair as for a map, and its .second says whether the key was new:

    #include <print>
    #include <set>
    #include <string>
    
    std::set<std::string> seen;
    for (std::string id : {"r1", "r7", "r1", "r3", "r7"}) {
        bool added = seen.insert(id).second;
        if (!added) {
            std::println("duplicate: {}", id);
        }
    }
    std::println("{}", seen);

    Output

    duplicate: r1
    duplicate: r7
    {"r1", "r3", "r7"}

    std::unordered_set<K> (from <unordered_set>) is the hash table version: no order, usually faster. Use it to ask “is this one of those?”:

    #include <print>
    #include <string>
    #include <unordered_set>
    
    std::unordered_set<char> bases = {'A', 'C', 'G', 'T'};
    std::string read = "GATNACA";
    for (char b : read) {
        if (!bases.contains(b)) {
            std::println("not a base: {}", b);
        }
    }

    Output

    not a base: N

    std::flat_map: a sorted map in two vectors

    std::flat_map<K, V> (from <flat_map>, new in C++23) works like std::map and keeps its keys sorted. But it stores them differently: all the keys in one vector and all the values in another, side by side. keys() and values() show the two vectors:

    #include <flat_map>
    #include <print>
    #include <string>
    
    std::flat_map<std::string, int> reads = {{"sample_b", 120},
                                             {"sample_a", 95}};
    reads["sample_c"] = 40;
    std::println("{}", reads);
    std::println("{}", reads.keys());
    std::println("{}", reads.values());

    Output

    {"sample_a": 95, "sample_b": 120, "sample_c": 40}
    ["sample_a", "sample_b", "sample_c"]
    [95, 120, 40]

    A lookup is a binary search in the sorted keys: look at the middle key, keep the half that can hold yours, repeat. Looping is as fast as looping over a vector. The cost is adding and removing: a new key in the middle moves every key and value after it, like insert on a vector.

    Modern C++flat_map needs a recent standard library

    <flat_map> and <flat_set> are new in C++23. GCC 15’s standard library has them; older ones don’t. std::flat_set is the set version.

    Which one should I use?

    WhatWhenWhyHow
    std::unordered_mapLooking values up by key, when order doesn’t matter.On average, a lookup takes about the same time however big the map gets.std::unordered_map<std::string, int> counts;
    std::mapYou need the keys in sorted order, or the smallest or largest key.The pairs are always sorted, so printing and looping are in key order.std::map<std::string, int> counts;
    std::flat_mapThe map is built once, then read many times.Keys and values sit in vectors: fast lookups and loops, little memory. Adding in the middle is slow.std::flat_map<std::string, int> table;
    std::unordered_set / std::setYou only need to know whether a key is present, or to drop duplicates.No values to store. std::set keeps the keys sorted.std::unordered_set<char> bases;

    Rule of thumb: reach for std::unordered_map for lookups, and switch to std::map when you need sorted keys, such as for printing.

    Under the hood

    std::map is a balanced tree. In GCC’s library each pair lives in its own heap block, called a node, with pointers to its parent and to two children: the side with smaller keys and the side with larger keys. A lookup starts at the top and goes left or right at each node, comparing with <. The tree is kept balanced, so a map of n keys takes about log₂ n steps: 20 steps for a million keys. Each step follows a pointer to another place in memory, which is slower than reading memory in order.

    std::unordered_map is an array of buckets. In GCC’s library, a key’s bucket is the remainder (%) of its hash divided by the number of buckets, and each bucket holds a short list of nodes. A lookup hashes the key and checks only the nodes in one bucket: about one, on average, however many keys there are. When there are more elements than buckets, the map allocates a bigger bucket array and relinks every node into its new bucket. The nodes themselves stay where they are, so references to elements stay valid, but the order you loop in changes:

    #include <print>
    #include <unordered_map>
    
    std::unordered_map<int, int> squares;
    std::println("buckets: {}", squares.bucket_count());
    for (int i = 0; i < 20; ++i) {
        squares[i] = i * i;
    }
    std::println("elements: {}, buckets: {}", squares.size(),
                 squares.bucket_count());

    Output

    buckets: 1
    elements: 20, buckets: 29

    Both kinds of map put each element in its own node on the heap. Here’s what one element costs in a map from int to int, with GCC’s standard library on this platform (64-bit Linux):

    One element of a map from int to int
    One element of a map from int to int: each row is one value; each cell's width is its size in bytes.
    Value0123456789101112131415161718192021222324252627282930313233343536373839Size
    std::map nodecolor4 bytes · tagpadding4 bytesparent8 bytes · pointerleft8 bytes · pointerright8 bytes · pointerkey4 bytesvalue4 bytes40 bytes
    std::unordered_map nodenext8 bytes · pointerkey4 bytesvalue4 bytes16 bytes
    std::flat_map entrykey4 bytesvalue4 bytes8 bytes

    With GCC's standard library on 64-bit Linux, a std::map node is 40 bytes: a 4-byte color used to keep the tree balanced, 4 bytes of padding, three 8-byte pointers (parent, left and right child), then the 4-byte key and the 4-byte value. A std::unordered_map node is 16 bytes: an 8-byte pointer to the next node in the bucket, then the key and the value. A std::flat_map stores only the 4-byte key in its keys vector and the 4-byte value in its values vector.

    So a std::map<int, int> spends 32 bytes on bookkeeping for every 8 bytes of data, plus whatever the memory allocator adds for each heap block. The std::unordered_map also has its bucket array. A std::flat_map stores nothing extra per element, and its keys sit next to each other in memory, which is why it’s the fastest to loop over.

    PerformanceReserve buckets when you know the size

    If you know roughly how many keys a std::unordered_map will hold, call m.reserve(n) first. It allocates enough buckets once, instead of relinking every node each time the map grows.

    Common pitfalls

    [] on a const map

    Because [] can add a key, it can’t be used on a const map, such as one passed by const&. GCC’s message says the call would drop the const (“discards qualifiers”):

    #include <map>
    #include <print>
    #include <string>
    
    int reads_for(const std::map<std::string, int>& reads,
                  const std::string& sample) {
        return reads[sample];
    }
    
    int main() {
        std::map<std::string, int> reads = {{"sample_a", 95}};
        std::println("{}", reads_for(reads, "sample_a"));
    }

    The compiler rejects this

    main.cpp: In function ‘int reads_for(const std::map<std::__cxx11::basic_string<char>, int>&, const std::string&)’:
    main.cpp:7:24: error: passing ‘const std::map<std::__cxx11::basic_string<char>, int>’ as ‘this’ argument discards qualifiers [-fpermissive]
        7 |     return reads[sample];
          |                        ^
    In file included from /usr/include/c++/15/map:65,
                     from main.cpp:1:
    /usr/include/c++/15/bits/stl_map.h:527:7: note:   in call to ‘std::map<_Key, _Tp, _Compare, _Alloc>::mapped_type& std::map<_Key, _Tp, _Compare, _Alloc>::operator[](const key_type&) [with _Key = std::__cxx11::basic_string<char>; _Tp = int; _Compare = std::less<std::__cxx11::basic_string<char> >; _Alloc = std::allocator<std::pair<const std::__cxx11::basic_string<char>, int> >; mapped_type = int; key_type = std::__cxx11::basic_string<char>]’
          |       operator[](const key_type& __k)
          |       ^~~~~~~~

    The fix is return reads.at(sample);, or find if a missing sample is normal and you want to handle it.

    Erasing while looping

    erase destroys the element and frees its node. If you’re looping over the map, the loop’s hidden iterator still points at that node, and moving to the next element reads freed memory. That’s undefined behavior, and AddressSanitizer catches it:

    #include <print>
    #include <string>
    #include <unordered_map>
    
    std::unordered_map<std::string, int> stock = {
        {"apples", 0}, {"pears", 4}, {"plums", 0}};
    for (const auto& [fruit, count] : stock) {
        if (count == 0) {
            stock.erase(fruit); // frees the node the loop is standing on
        }
    }
    std::println("{}", stock);

    This fails when it runs

    ERROR: AddressSanitizer: heap-use-after-free on address 0x…
    READ of size 8 at 0x… thread T0
        #0 std::__detail::_Hash_node<std::pair<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const, int>, true>::_M_next() const
           … 2 frames inside the standard library
        #3 main main.cpp:7
    
    0x… is located 0 bytes inside of 56-byte region [0x…,0x…)
    freed by thread T0 here:
        #0 operator delete(void*, unsigned long)
           … 8 frames inside the standard library
        #9 main main.cpp:9
    
    previously allocated by thread T0 here:
        #0 operator new(unsigned long)
           … 9 frames inside the standard library
        #10 main main.cpp:6
    
    SUMMARY: AddressSanitizer: heap-use-after-free main.cpp:7 in main

    The same loop over a std::map is just as wrong, even when it seems to work. On this platform AddressSanitizer doesn’t catch that version: the step to the next node happens inside the precompiled standard library, which the sanitizer can’t see.

    The fix is std::erase_if (C++20), which removes every element a predicate accepts, safely, as it does for a vector. For a map, the predicate gets each element as a std::pair of a const key and a value:

    #include <print>
    #include <string>
    #include <unordered_map>
    #include <utility>
    
    bool sold_out(const std::pair<const std::string, int>& item) {
        return item.second == 0;
    }
    
    int main() {
        std::unordered_map<std::string, int> stock = {
            {"apples", 0}, {"pears", 4}, {"plums", 0}};
        std::erase_if(stock, sold_out);
        std::println("{}", stock);
    }

    Output

    {"pears": 4}

    Try it yourself

    Try it yourself

    Count how many times each 3-mer (substring of length 3) appears in dna. The loop already takes every 3-mer with substr. Make it count them in the std::map, so the program prints each 3-mer with its count, then the number of different 3-mers.

    #include <cstddef>
    #include <map>
    #include <print>
    #include <string>
    
    int main() {
        std::string dna = "GATTACAGATTACA";
        std::size_t k = 3;
        std::map<std::string, int> counts;
        for (std::size_t i = 0; i + k <= dna.size(); ++i) {
            std::string kmer = dna.substr(i, k);
            // count kmer here
        }
        std::println("{}", counts);
        std::println("{} different", counts.size());
    }

    Expected output

    {"ACA": 2, "AGA": 1, "ATT": 2, "CAG": 1, "GAT": 2, "TAC": 2, "TTA": 2}
    7 different
    Show a hint

    Inside the loop, ++counts[kmer] adds the k-mer with 0 the first time and then counts it. A std::map prints its keys in sorted order.

    Show a solution
    #include <cstddef>
    #include <map>
    #include <print>
    #include <string>
    
    int main() {
        std::string dna = "GATTACAGATTACA";
        std::size_t k = 3;
        std::map<std::string, int> counts;
        for (std::size_t i = 0; i + k <= dna.size(); ++i) {
            std::string kmer = dna.substr(i, k);
            ++counts[kmer];
        }
        std::println("{}", counts);
        std::println("{} different", counts.size());
    }

    counts[kmer] adds a missing k-mer with the value 0, and ++ makes it 1; a k-mer seen before just goes up by one. The sequence has 12 positions where a 3-mer starts (14 - 3 + 1), and the map shows 7 different 3-mers whose counts add up to 12. Because it's a std::map, they print in alphabetical order.

    Saved in this browser only.