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

unordered_set & unordered_map in C++

//concept

unordered_set and unordered_map are hash tables: average O(1) insert, find, and erase with no ordering guarantees. Keys need a hash (std::hash covers built-ins and strings) and equality — custom types supply both, and poor hashes degrade toward O(n) buckets.

Choose unordered for pure lookup speed (caches, indexes, visited-sets) and ordered map/set when you iterate in key order or need range queries. Rehashing grows the table automatically; reserve() avoids the hiccups when the final size is known.

//how it works
1

Average O(1), unordered

Hashing jumps straight to the bucket — faster than trees for lookup, but iteration order is unspecified and unstable.

2

Keys need hash + equality

Built-ins and std::string work out of the box; custom keys need a hash functor and operator==.

3

Same access idioms

find/at/operator[] mirror map — including the operator[]-inserts-on-miss footgun, so lookup-only code still prefers find().

4

Tune with reserve

table.reserve(100000); pre-sizes buckets, skipping repeated rehashes during bulk loads.

//example
#include <iostream>
#include <unordered_map>
#include <string>
 
int main() {
std::unordered_map<std::string, int> score;
score["ada"] = 95;
score["grace"] = 99;
auto it = score.find("ada");
std::cout << score.size() << ", " << it->second << std::endl;
return 0;
}
Output
2, 95
1Two key-value pairs hash into buckets — average O(1) each, order unspecified.
2find("ada") returns an iterator to the pair without inserting anything.
3it->second reads the mapped value 95; size reports 2 entries.
//complexity
time O(1) average insert/find/erase
space O(n)

Hash table; worst case O(n) on pathological hashing.

//use cases
Lookup caches and memo tables where speed beats ordering
Visited-sets in BFS/DFS over string or custom-node graphs
Frequency counting in a single pass with operator[] accumulation
Custom-key indexes with a hand-rolled hash combining member hashes

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.