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.
#include <map>
std::map<std::string, int> ages;
ages["Ana"] = 25;
std::cout << ages["Ana"];25map stores key-value pairs accessible with [].
#include <set>
std::set<int> s = {3, 1, 2, 1};
for (int x : s) std::cout << x;123set 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.
