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.
#include <unordered_map>
#include <string>
#include <iostream>
int main() {
// Create an unordered_map
std::unordered_map<std::string, int> 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
for (const auto& [name, age] : ages) {
std::cout << name << " is " << age << " years old" << std::endl;
}
return 0;
}
For custom types as keys, you need to provide a hash function and equality operator:
struct Person {
std::string name;
int age;
bool operator==(const Person& other) const {
return name == other.name && age == other.age;
}
};
// Custom hash function
struct PersonHash {
std::size_t operator()(const Person& p) const {
return std::hash<std::string>()(p.name) ^ std::hash<int>()(p.age);
}
};
// Usage
std::unordered_map<Person, std::string, PersonHash> personData;
std::unordered_map
is generally preferred over std::map
when order doesn’t matter and you need faster lookups for large datasets.