C++ unordered_map
In this page:
What is unordered_map?
std::unordered_map is an associative container storing key-value pairs with no guaranteed order, implemented as a hash table. Average-case lookup, insertion, and deletion run in O(1) time, faster than map for most workloads that do not need sorted keys.
Example: What is unordered_map?
#include <iostream>
#include <unordered_map>
#include <string>
int main() {
std::unordered_map<std::string, int> ages;
ages["Alex"] = 30;
std::cout << ages["Alex"] << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Accessing Elements
Like map, unordered_map supports operator[] and at() for access. Since there is no ordering, elements are retrieved purely by key, not by position.
Example: Accessing Elements
#include <iostream>
#include <unordered_map>
#include <string>
int main() {
std::unordered_map<std::string, int> ages = {{"Alex", 30}};
std::cout << ages.at("Alex") << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Hashing & Performance
unordered_map hashes each key to determine its bucket. This gives average O(1) operations but worst-case O(n) if many keys collide. bucket_count() and load_factor() expose the internal hash table state.
Example: Hashing & Performance
#include <iostream>
#include <unordered_map>
int main() {
std::unordered_map<int, int> m;
m[1] = 10;
std::cout << "buckets=" << m.bucket_count() << " load_factor=" << m.load_factor() << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Iterating (Unordered)
Iterating an unordered_map visits elements in an unspecified, implementation-defined order that can change between insertions. Never rely on iteration order for correctness.
Example: Iterating (Unordered)
#include <iostream>
#include <unordered_map>
int main() {
std::unordered_map<int, int> m = {{1, 10}, {2, 20}};
for (const auto &[key, value] : m) {
std::cout << key << ":" << value << " ";
}
std::cout << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Searching and Erasing
find(), count(), and erase() work the same way as std::map, but rely on hashing rather than tree traversal, making them faster on average for large unsorted datasets.
Example: Searching and Erasing
#include <iostream>
#include <unordered_map>
int main() {
std::unordered_map<int, int> m = {{1, 10}};
auto it = m.find(1);
if (it != m.end()) std::cout << "Found: " << it->second << std::endl;
m.erase(1);
std::cout << m.size() << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 15 topics to unlock
0/15 topics done
Complete these topics first: