unordered_set & unordered_map in C++
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.
Average O(1), unordered
Hashing jumps straight to the bucket — faster than trees for lookup, but iteration order is unspecified and unstable.
Keys need hash + equality
Built-ins and std::string work out of the box; custom keys need a hash functor and operator==.
Same access idioms
find/at/operator[] mirror map — including the operator[]-inserts-on-miss footgun, so lookup-only code still prefers find().
Tune with reserve
table.reserve(100000); pre-sizes buckets, skipping repeated rehashes during bulk loads.
#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;}Hash table; worst case O(n) on pathological hashing.
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.