--- title: "std::unordered_map in C++" description: "std::unordered_map in C++: a hash table with average O(1) lookup, insert and erase, basic usage, and custom hash functions for user-defined keys." date: 2023-04-06 last_modified_at: 2026-10-02 keywords: [C++, std::unordered_map, hash table, custom hash, STL] --- # Unordered Map in C++ `std::unordered_map` is a container that stores key-value pairs in which keys are unique. It implements a hash table, providing average constant-time complexity for search, insert, and delete operations. ## Basic Usage ```cpp #include #include #include int main() { // Create an unordered_map std::unordered_map ages; // Insert elements ages["Alice"] = 30; ages["Bob"] = 25; ages.insert({"Charlie", 35}); // Access elements std::cout << "Alice's age: " << ages["Alice"] << std::endl; // Check if key exists if (ages.find("David") == ages.end()) { std::cout << "David not found" << std::endl; } // Iterate through all elements (structured bindings need C++17) for (const auto& [name, age] : ages) { std::cout << name << " is " << age << " years old" << std::endl; } return 0; } ``` ## Custom Hash Functions For custom types as keys, you need to provide a hash function and equality operator: ```cpp struct Person { std::string name; int age; bool operator==(const Person& other) const { return name == other.name && age == other.age; } }; // Custom hash function. XOR is the simplest way to combine hashes but collides easily // (equal component hashes cancel out to 0); boost::hash_combine-style mixing is safer. struct PersonHash { std::size_t operator()(const Person& p) const { return std::hash()(p.name) ^ std::hash()(p.age); } }; // Usage std::unordered_map personData; ``` `std::unordered_map` is generally preferred over `std::map` when order doesn't matter and you need faster lookups for large datasets.