std::map
std::map<K, V> is an ordered dictionary: each key appears once, keys stay sorted, and lookup, insert, and erase are O(log n). It is usually a balanced binary tree (red-black on every mainstream library).
Detailed Explanation
You are keeping users by id and you need them in id order for a report, plus fast lookup by id. std::map<int, User> does both. std::unordered_map is faster on average for lookup and does not keep order. Pick map when you need order, when keys do not have a hash, or when you need lower_bound on the key.
The node holds a std::pair<const K, V>. The key is const because changing it would break the tree. it->first is the key, it->second is the value. Structured bindings give you const auto& [id, user] = *it.
Lookup: m.find(k) returns an iterator or end(). m.at(k) returns a reference or throws std::out_of_range. m[k] default-constructs a V if the key is missing and returns a reference to it. That last behaviour is convenient and is the source of most map bugs: a read-only query written as m[k] inserts. On a const map, operator[] does not exist.
Insert: emplace(k, v), insert({k, v}), insert_or_assign (C++17), try_emplace (C++17, does not move from the value if the key exists). insert of an existing key does not overwrite. m[k] = v overwrites or inserts.
Iteration is in key order, according to the comparator (default std::less<K>). lower_bound(k) is the first element not less than k. upper_bound(k) is the first greater than k. equal_range is both. Those are the APIs that make a map a sorted index, not just a dictionary.
The comparator must define a strict weak ordering. <= is wrong; use <. Equal keys compare false both ways. A comparator that reads a mutating field will corrupt the tree.
Iterators to other elements stay valid on insert and erase, except the erased element's iterator. Pointers and references to elements stay valid too: nodes do not move. That is the advantage over unordered_map rehash and over vector of pairs.
Cost: each element is a heap node with at least two child pointers, a parent, and a colour bit. Walking a map is pointer-chasing. A vector<pair<K, V>> that you keep sorted can beat a small map. Profile before you replace a map of twenty items.
std::multimap allows duplicate keys. std::map does not.
Code Examples
#include <iostream>
#include <map>
#include <string>
int main() {
std::map<std::string, int> ages;
ages["ada"] = 36; // inserts
ages["al"] = 46;
ages.insert({"ada", 99}); // ignored: key exists
std::cout << ages["ada"] << '\n'; // prints: 36
if (auto it = ages.find("grace"); it == ages.end()) {
std::cout << "missing\n"; // prints: missing
}
for (const auto& [name, age] : ages) {
std::cout << name << ' ';
}
std::cout << '\n'; // prints: ada al
}#include <iostream>
#include <map>
int main() {
std::map<int, const char*> ports{{80, "http"}, {443, "https"}, {8080, "alt"}};
auto it = ports.lower_bound(100);
std::cout << it->first << '\n'; // prints: 443
}Common Gotchas
`operator[]` inserts
`int n = m[k];` on a missing key default-constructs a value. Use `find` or `at` for queries. `V` must be default-constructible for `[]` to compile.
Mutating `it->first`
the key is `const`. To "rename" a key, extract (C++17 `extract`), change, and insert again.
A bad comparator silently corrupts the tree
comparators must be consistent and must not change after insert.
`try_emplace` is the insert that does not move the mapped value on a collision
use it when the value is a `unique_ptr` you do not want to lose.