Learn C++
#include "stlcontainers/set_map.hpp"

set & map in C++

//concept

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).

//how it works
1

Sorted and unique

Inserting a duplicate into set/map is a no-op (check the returned bool/pair) — uniqueness enforced structurally.

2

O(log n) everything

Insert, find, erase, and count all cost logarithmic — predictable from ten elements to ten million.

3

Order-powered queries

lower_bound finds the first element not less than a key — floor/ceiling, ranges, and prefix scans in one call.

4

map access patterns

m[k] inserts a default if missing (often a bug!); prefer find() or at() for lookup-only access.

//example
#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;
}
Output
36, 2, 1
1operator[] inserts-or-assigns: ada→36 and grace→85 entries appear on first use.
2The set keeps {1, 3} — the duplicate 3 collapses, size reports 2, and begin() yields the smallest, 1.
336, 2, 1 prints — map lookup, set uniqueness, and sorted order in one line.
//complexity
time O(log n) insert/find/erase
space O(n)

Red-black tree; iteration visits keys in sorted order.

//use cases
Dictionaries, configs, and frequency tables with map
Deduplication and membership tests with set
Ordered statistics via lower_bound/upper_bound neighbors
Deterministic output order for tests and reports

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in C++ yourself — building beats watching.