STL Map

STL Map in C++: A vector is a numbered list: to find something you either know its position or you read from the top until you spot it.

The Analogy: A Dictionary, Not a Numbered List

A vector is a numbered list: to find something you either know its position or you read from the top until you spot it. Ask "where is the entry for gasket?" and a vector has to look at every element.

A std::map is a dictionary. You do not look up the word "gasket" by counting pages; you go straight to the G section, because a dictionary is organised by its keys. Every entry is a pair — the word and its definition, the key and the value — and the book keeps itself in alphabetical order whether you like it or not. Add "flange" and it slots in between "eagle" and "gasket" automatically.

Two consequences fall out of that image and explain almost everything about std::map:

  • Lookup is by key, not position. prices["gasket"] asks a question about meaning, not about layout.
  • Keys are unique and always sorted. A dictionary has one entry per word, and iterating a map always walks the keys in order — which is a feature you get for free and cannot turn off.

If you do not need the sorted order, std::unordered_map is the same idea built on a hash table and is usually faster. We will cover both.


Syntax or Core Structure

#include <iostream>
#include <map>
#include <string>

int main() {
    std::map<std::string, double> prices;

    // Inserting -- four ways
    prices["widget"] = 4.99;                        // subscript: create or overwrite
    prices.insert({"gasket", 1.25});                // ignored if key exists
    prices.emplace("flange", 8.50);                 // constructs in place
    prices.insert_or_assign("bolt", 0.35);          // create or overwrite, explicit

    // Or all at once
    std::map<std::string, int> stock{
        {"widget", 12},
        {"gasket", 40},
        {"flange", 3}
    };

    // Reading
    std::cout << "widget: " << prices["widget"] << "\n";
    std::cout << "count:  " << prices.size() << "\n";
    std::cout << "empty?  " << (prices.empty() ? "yes" : "no") << "\n";

    // Does a key exist? (C++20)
    if (prices.contains("gasket")) {
        std::cout << "we sell gaskets\n";
    }

    // Pre-C++20, and still the way to get the value at the same time
    auto it = prices.find("flange");
    if (it != prices.end()) {
        std::cout << "flange: " << it->second << "\n";
    } else {
        std::cout << "no flange\n";
    }

    // Iterating -- ALWAYS in sorted key order
    for (const auto& [name, price] : prices) {         // C++17 structured binding
        std::cout << name << " = " << price << "\n";
    }

    // Pre-C++17 form
    for (std::map<std::string, double>::const_iterator i = prices.begin();
         i != prices.end(); ++i) {
        std::cout << i->first << " -> " << i->second << "\n";
    }

    // Updating
    prices["widget"] += 1.00;                          // 5.99
    prices.at("gasket") = 1.50;                        // bounds-checked

    // Removing
    prices.erase("bolt");
    std::cout << "after erase: " << prices.size() << "\n";
    prices.clear();
}

Output (note the alphabetical order):

widget: 4.99
count:  4
we sell gaskets
flange: 8.5
bolt = 0.35
flange = 8.5
gasket = 1.25
widget = 4.99

The keys came out bolt, flange, gasket, widget even though they went in as widget, gasket, flange, bolt. That is the map sorting itself.


Technical Depth: The Subscript Trap and What to Use Instead

operator[] inserts

This is the single most surprising thing about std::map, and the source of more bugs than the rest of the container combined:

std::map<std::string, int> stock{{"widget", 12}};

std::cout << stock.size() << "\n";        // 1
std::cout << stock["gasket"] << "\n";     // prints 0 -- and INSERTS gasket
std::cout << stock.size() << "\n";        // 2

Reading a missing key with [] silently creates it with a value-initialised value: 0 for an int, 0.0 for a double, "" for a std::string. Nothing warns you. A loop that "just checks" a thousand keys leaves you with a thousand entries.

Worse, it will not compile at all on a const map, because inserting is a modification:

void report(const std::map<std::string, int>& stock) {
    // std::cout << stock["widget"];      // ERROR: [] is non-const
    std::cout << stock.at("widget");      // fine -- but throws if missing
}

The four ways to read, and when each is right

ApproachMissing key behaviourWorks on const mapUse when
m[key]Inserts a defaultNoYou want create-or-update
m.at(key)Throws std::out_of_rangeYesKey must exist; absence is a bug
m.contains(key)Returns false (C++20)YesYou only need yes/no
m.find(key)Returns end()YesYou need existence and the value

find is the workhorse, because it answers both questions with one lookup:

auto it = stock.find("gasket");
if (it != stock.end()) {
    it->second += 5;                       // found: use and modify it
} else {
    stock.emplace("gasket", 5);            // not found
}

Writing if (stock.contains(k)) use(stock.at(k)); searches the tree twice. find searches once.

The one place [] shines: counting

std::map<char, int> frequency;
for (char c : std::string("mississippi")) {
    ++frequency[c];                        // missing -> 0, then incremented to 1
}
// i=4, m=1, p=2, s=4

Here the insert-on-read behaviour is exactly what you want, and the idiom is deliberate rather than accidental.

insert versus [] versus insert_or_assign

std::map<std::string, int> m{{"a", 1}};

m.insert({"a", 99});              // NO-OP -- key exists, value stays 1
m["a"] = 99;                      // overwrites -- now 99
m.insert_or_assign("a", 7);       // overwrites -- now 7, and says so in the name

insert returning a no-op for existing keys catches people out constantly. It does tell you what happened:

auto [it, inserted] = m.insert({"b", 2});
if (!inserted) std::cout << "b already existed with value " << it->second << "\n";

What a pair looks like from the inside

A map element is a std::pair<const Key, Value>. Note the const on the key — you cannot rename a key in place, because that would break the sort order. Change a key by erasing and re-inserting.

for (auto& entry : stock) {
    // entry.first += "!";                 // ERROR: key is const
    entry.second += 1;                     // fine
}

Structured bindings make this readable, and auto& versus const auto& controls whether you may write:

for (const auto& [name, count] : stock) { /* read only */ }
for (auto& [name, count] : stock)       { count *= 2; }    // modifies values

Removing while iterating

erase invalidates only the iterator to the erased element, so the safe loop uses erase's return value:

for (auto it = stock.begin(); it != stock.end(); ) {
    if (it->second == 0) {
        it = stock.erase(it);              // returns the NEXT iterator
    } else {
        ++it;
    }
}

Do not write stock.erase(it); ++it; — that increments a dead iterator. In C++20 the whole loop is std::erase_if(stock, [](const auto& e) { return e.second == 0; });.

map versus unordered_map

std::mapstd::unordered_map
Built onBalanced binary treeHash table
Lookup costO(log n)O(1) average, O(n) worst
Iteration orderSorted by keyUnspecified, appears random
Key requiresoperator<std::hash and operator==
Header<map><unordered_map>
MemoryLower overhead per elementHigher, plus buckets

They share almost their whole interface, so switching is usually a one-line change. Default to std::unordered_map when you do not care about order; use std::map when you want sorted iteration, or need lower_bound-style range queries, or your key type has < but no hash.

Ordered-only operations

Because std::map is sorted, it can answer range questions a hash table cannot:

std::map<int, std::string> log{{100, "boot"}, {250, "load"}, {400, "ready"}};

auto lo = log.lower_bound(150);              // first key >= 150  -> 250
auto hi = log.upper_bound(400);              // first key > 400   -> end()
for (auto it = lo; it != hi; ++it) {
    std::cout << it->first << ": " << it->second << "\n";
}

std::cout << "earliest: " << log.begin()->first << "\n";
std::cout << "latest:   " << log.rbegin()->first << "\n";

Custom keys and custom ordering

A std::map key needs operator<. For your own type, supply one — or pass a comparator:

std::map<std::string, int, std::greater<std::string>> descending;   // reverse order

Duplicate keys, and maps of collections

std::map allows one value per key. When a key needs several values, do not reach for std::multimap first — a map of vectors is usually clearer:

std::map<std::string, std::vector<std::string>> byAuthor;
byAuthor["Ada"].push_back("Notes on the Engine");    // [] creates the empty vector
byAuthor["Ada"].push_back("Sketch of the Analytical Engine");

That is another legitimate use of the insert-on-read behaviour: the missing entry is created as an empty vector, and push_back fills it.


Real World Example: A Word Frequency Report

Counting things by name is what maps are for. This program takes a block of text, tallies word frequencies, groups words by their first letter, and prints the results — exercising every access pattern from the section above, each in the place where it is actually the right one.

#include <algorithm>
#include <cctype>
#include <iomanip>
#include <iostream>
#include <map>
#include <optional>
#include <sstream>
#include <string>
#include <vector>

std::string normalise(const std::string& raw) {
    std::string out;
    for (char c : raw) {
        if (std::isalpha(static_cast<unsigned char>(c))) {
            out += static_cast<char>(std::tolower(static_cast<unsigned char>(c)));
        }
    }
    return out;
}

std::map<std::string, int> tally(const std::string& text) {
    std::map<std::string, int> counts;
    std::istringstream in(text);
    std::string raw;
    while (in >> raw) {
        std::string word = normalise(raw);
        if (word.empty()) continue;
        ++counts[word];                              // [] on purpose: 0 then ++
    }
    return counts;
}

std::optional<int> countOf(const std::map<std::string, int>& counts,
                           const std::string& word) {
    auto it = counts.find(word);                     // find: existence AND value
    if (it == counts.end()) return std::nullopt;
    return it->second;
}

std::map<char, std::vector<std::string>> groupByLetter(
        const std::map<std::string, int>& counts) {
    std::map<char, std::vector<std::string>> groups;
    for (const auto& [word, count] : counts) {
        groups[word.front()].push_back(word);        // [] creates the empty vector
    }
    return groups;
}

std::vector<std::pair<std::string, int>> topWords(
        const std::map<std::string, int>& counts, std::size_t howMany) {
    std::vector<std::pair<std::string, int>> ranked(counts.begin(), counts.end());
    std::sort(ranked.begin(), ranked.end(),
              [](const auto& a, const auto& b) {
                  if (a.second != b.second) return a.second > b.second;
                  return a.first < b.first;          // ties broken alphabetically
              });
    if (ranked.size() > howMany) ranked.resize(howMany);
    return ranked;
}

void dropRareWords(std::map<std::string, int>& counts, int minimum) {
    for (auto it = counts.begin(); it != counts.end(); ) {
        if (it->second < minimum) {
            it = counts.erase(it);                   // erase returns the next one
        } else {
            ++it;
        }
    }
}

int main() {
    const std::string text =
        "the quick brown fox jumps over the lazy dog. "
        "The dog barks; the fox runs. A quick fox, a lazy dog.";

    std::map<std::string, int> counts = tally(text);

    std::cout << "distinct words: " << counts.size() << "\n\n";

    std::cout << "-- alphabetical (maps iterate sorted) --\n";
    for (const auto& [word, count] : counts) {
        std::cout << "  " << std::left << std::setw(8) << word << count << "\n";
    }

    std::cout << "\n-- top 3 by frequency --\n";
    for (const auto& [word, count] : topWords(counts, 3)) {
        std::cout << "  " << std::left << std::setw(8) << word << count << "\n";
    }

    std::cout << "\n-- lookups --\n";
    for (const std::string& probe : {"fox", "cat"}) {
        if (auto n = countOf(counts, probe)) {
            std::cout << "  " << probe << " appears " << *n << " times\n";
        } else {
            std::cout << "  " << probe << " does not appear\n";
        }
    }
    std::cout << "  distinct words still " << counts.size()
              << " (find did not insert)\n";

    std::cout << "\n-- grouped by first letter --\n";
    for (const auto& [letter, words] : groupByLetter(counts)) {
        std::cout << "  " << letter << ": ";
        for (const std::string& w : words) std::cout << w << " ";
        std::cout << "\n";
    }

    std::cout << "\n-- words used at least twice --\n";
    dropRareWords(counts, 2);
    for (const auto& [word, count] : counts) {
        std::cout << "  " << std::left << std::setw(8) << word << count << "\n";
    }
}

Output (abridged):

distinct words: 11

-- alphabetical (maps iterate sorted) --
  a       2
  barks   1
  brown   1
  dog     3
  fox     3
  ...

-- top 3 by frequency --
  the     4
  dog     3
  fox     3

-- lookups --
  fox appears 3 times
  cat does not appear
  distinct words still 11 (find did not insert)

-- grouped by first letter --
  a: a
  b: barks brown
  d: dog
  ...

-- words used at least twice --
  a       2
  dog     3
  fox     3
  lazy    2
  quick   2
  the     4

The access patterns are chosen, not incidental. tally uses ++counts[word] because the insert-on-read behaviour is precisely what counting wants: a word seen for the first time appears as 0 and is immediately incremented to 1, no existence check required. groupByLetter uses groups[word.front()] for the same reason one level up — the missing entry is created as an empty vector, ready to push_back into. Those are the two idioms where [] is the right tool.

countOf, by contrast, must not use []. It is a query, its map parameter is const, and [] would not even compile there; more importantly, probing "cat" with [] would silently add cat -> 0 to the report. It uses find rather than contains plus at because it needs the value as well as the answer, and find gets both from one tree walk. It returns std::optional<int> because "absent" and "present zero times" are genuinely different facts and 0 cannot express both. The printed distinct words still 13 line exists to prove the point.

topWords shows the map's one real limitation: it is sorted by key, and there is no way to ask it for the largest values. So it copies the entries into a std::vector<std::pair<...>> and sorts that with a comparator — descending by count, then ascending by word so ties are stable and reproducible rather than arbitrary. Note that the vector's element type drops the const from the key, which is what makes it sortable in the first place; you could not reorder the map's own nodes. dropRareWords uses the it = counts.erase(it) loop, the only correct way to erase during iteration before C++20 — writing counts.erase(it); ++it; increments an iterator that is already dead.

One last point: every iteration in this program comes out sorted without a single sort call, because that is what std::map guarantees. Swap it for std::unordered_map and every lookup gets faster while every listing comes out in an unpredictable order. Which container is right depends entirely on whether that order is part of the output you promised.


Common Mistakes

  1. Reading with []. m["missing"] inserts a default-valued entry. Use find, at or contains to query.
  2. Calling [] on a const map. It will not compile, because [] may insert. Use at or find.
  3. Expecting insert to overwrite. It does nothing if the key exists. Use [] or insert_or_assign.
  4. contains followed by at. Two lookups where find needs one.
  5. Trying to modify a key. entry.first is const. Erase and re-insert instead.
  6. erase(it); ++it; — the iterator is invalid after the erase. Use it = m.erase(it);.
  7. Assuming insertion order is preserved. std::map sorts by key; std::unordered_map has no order at all. Neither remembers what you did first.
  8. Using at on data from outside. It throws std::out_of_range. Wrap it, or use find.
  9. Sorting a map by value in place. Impossible — copy into a vector of pairs and sort that.
  10. Reaching for std::multimap when std::map<Key, std::vector<Value>> would be clearer and easier to work with.

Best Practices

  • Default to std::unordered_map unless you need sorted iteration or range queries; then use std::map.
  • Use find for queries, [] for create-or-update, at when absence is a bug.
  • ++m[key] is the correct counting idiom — lean on insert-on-read deliberately, never accidentally.
  • Structured bindings for iteration. for (const auto& [k, v] : m) beats it->first / it->second.
  • const auto& to read, auto& to modify values. Never plain auto, which copies every entry.
  • Take const std::map<K, V>& in functions that only read.
  • Check the bool from insert when whether it happened matters: auto [it, ok] = m.insert(...).
  • Prefer std::erase_if in C++20, the it = erase(it) loop before it.
  • Give custom key types a correct operator< — a wrong one corrupts the map silently.

Practice Exercises

  1. Write a program that reads names from the user until they enter done, counting how many times each was entered with a std::map<std::string, int>, then prints the tallies. Explain why ++counts[name] needs no existence check.
  2. Write std::optional<double> priceOf(const std::map<std::string, double>&, const std::string&) using find. Then write a broken version with [] and demonstrate that calling it grows the map.
  3. Given a std::map<std::string, int> of exam scores, produce a std::vector<std::pair<std::string, int>> sorted highest score first, ties alphabetical. Explain why the sorting cannot be done in the map itself.
  4. Build a std::map<std::string, std::vector<std::string>> mapping each category to its products. Add products to three categories, print the whole structure, then delete every category with fewer than two products using the it = erase(it) loop.