std::unordered_map
Fast hash-based lookup.
What Is unordered_map?
std::unordered_map stores key-value pairs in a hash table. Average lookup, insert, and erase are constant time, but elements have no sorted order.
#include <iostream>
#include <unordered_map>
int main() {
std::unordered_map<std::string, int> ages;
ages["Alice"] = 30;
ages["Bob"] = 25;
std::cout << ages["Alice"] << '\n';
return 0;
}map vs unordered_map
Choose based on needs:
map: sorted, O(log n) operations.unordered_map: unordered, O(1) average operations.
Use unordered_map when you only need fast lookups.
#include <iostream>
#include <unordered_map>
int main() {
std::unordered_map<int, std::string> m{{3, "c"}, {1, "a"}, {2, "b"}};
std::cout << m.size() << " entries (order not guaranteed)\n";
return 0;
}All lessons in this course
- std::unordered_map
- unordered_set
- Custom Hash Functions
- Performance Considerations