C++ ยท Chapter 44 of 49

C++ STL Map and Set

`std::map<K,V>` stores unique key-value pairs sorted by key, while `std::set<T>` stores unique sorted values. Both use a balanced tree internally, giving O(log n) insert/find/erase operations.

For faster average-case performance without ordering guarantees, `std::unordered_map` and `std::unordered_set` use hash tables instead, offering roughly O(1) average lookups.

Using std::map

`map["key"] = value;` inserts or updates; `map.find("key")` searches; `map.count("key")` checks existence (0 or 1).

Using std::set

`set.insert(5);` adds a value if not already present. Sets automatically keep elements unique and sorted, useful for deduplication.

Example 1 (cpp)
#include <map>
std::map<std::string, int> ages;
ages["Ana"] = 25;
std::cout << ages["Ana"];
Output
25

map stores key-value pairs accessible with [].

Example 2 (cpp)
#include <set>
std::set<int> s = {3, 1, 2, 1};
for (int x : s) std::cout << x;
Output
123

set removes the duplicate 1 and keeps elements sorted.

Key points

  • map stores sorted, unique key-value pairs.
  • set stores sorted, unique values.
  • unordered_map/unordered_set trade ordering for faster average lookups.
  • Both support insert, find, count, and erase.
๐Ÿ’ก Note: Using map["key"] on a missing key silently inserts it with a default value โ€” use .find() if you just want to check existence.

๐Ÿ“ Quick Quiz

1. What does std::map store?

2. Which container guarantees average O(1) lookup?

3. std::set automatically: