A high-level, general-purpose programming language, created as an extension of the C programming language, that has object-oriented, generic, and functional features in addition to facilities for low-level memory manipulation.
Use std::unordered_map<Key, Value> to create a C++ hash table; it applies std::hash<Key> automatically and provides insert, find, and erase for the required operations.^1^
Complete example
#include <iostream>
#include <string>
#include <unordered_map>
int main() {
std::unordered_map<int, std::string> students;
// Insert
students.insert({101, "Ali"});
students.emplace(102, "Sara");
students[103] = "Ahmed";
// Search
int key = 102;
auto it = students.find(key);
if (it != students.end())
std::cout << "Found: " << it->second << '\n';
else
std::cout << "Not found\n";
// Delete
std::cout << "Removed: " << students.erase(101) << '\n';
// Display remaining entries
for (const auto& [id, name] : students)
std::cout << id << ": " << name << '\n';
}
Compile with C++17 or later:
cl /EHsc /std:c++17 main.cpp
How each operation behaves
- Insert:
insert({key, value})adds the entry only if the key does not already exist.emplaceconstructs the entry in place. - Insert or update:
table[key] = valueinserts a missing key or replaces the value associated with an existing key. For a missing key,operator[]first creates a default-initialized value. - Search:
find(key)returns an iterator to the entry, orend()when the key is absent. - Delete:
erase(key)returns the number of removed entries—normally1or0, becauseunordered_maphas unique keys.^1^ - Read with bounds checking:
at(key)returns the value but throwsstd::out_of_rangeif the key is absent. - Existence check: With C++20,
contains(key)is a simpler Boolean test.
How hashing works
The hash function converts a key into a std::size_t. The container uses that result to select a bucket. Different keys can select the same bucket; this is a collision, and the equality function distinguishes those keys.
When buckets remain reasonably balanced, insertion, search, and deletion can be constant-time on average. If many entries fall into one bucket, an operation can degrade to linear time. The container monitors its load factor and rebuilds its buckets when necessary.^1^
You can inspect the hash and bucket chosen for a key:
auto hash = students.hash_function();
std::cout << "Hash: " << hash(102) << '\n';
std::cout << "Bucket: " << students.bucket(102) << '\n';
std::cout << "Buckets: " << students.bucket_count() << '\n';
Do not depend on iteration order: unordered_map does not guarantee that entries appear in insertion or sorted order.
Custom key and hash function
A custom hash is needed when the key is a user-defined type:
struct StudentKey {
int school;
int id;
bool operator==(const StudentKey& x) const {
return school == x.school && id == x.id;
}
};
struct StudentHash {
std::size_t operator()(const StudentKey& x) const {
return std::hash<int>{}(x.school)
^ (std::hash<int>{}(x.id) << 1);
}
};
std::unordered_map<StudentKey, std::string, StudentHash> students;
Equal keys must always produce the same hash value. Unequal keys may produce the same hash—the container handles that collision using operator==. The Hash and equality predicate are explicit template parameters of unordered_map.^1^
If only keys are needed, without associated values, use std::unordered_set instead.
References