set & map in C++
std::set keeps unique keys sorted; std::map keeps unique key→value pairs sorted by key — both red-black trees with O(log n) insert, erase, and find, plus ordered traversal for free. Sorted order is the superpower: range queries, neighbors (lower_bound/upper_bound), and deterministic output come at no extra code.
Multi- variants (multiset, multimap) allow duplicates. Custom ordering arrives via operator< on the key type or an explicit comparator. When order doesn't matter, unordered_* trades the sorting for average O(1).
Sorted and unique
Inserting a duplicate into set/map is a no-op (check the returned bool/pair) — uniqueness enforced structurally.
O(log n) everything
Insert, find, erase, and count all cost logarithmic — predictable from ten elements to ten million.
Order-powered queries
lower_bound finds the first element not less than a key — floor/ceiling, ranges, and prefix scans in one call.
map access patterns
m[k] inserts a default if missing (often a bug!); prefer find() or at() for lookup-only access.
#include <iostream>#include <map>#include <set> int main() { std::map<std::string, int> age; age["ada"] = 36; age["grace"] = 85; std::set<int> s{3, 1, 3}; std::cout << age["ada"] << ", " << s.size() << ", " << *s.begin() << std::endl; return 0;}Red-black tree; iteration visits keys in sorted order.
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in C++ yourself — building beats watching.