Junior — Middle
How are elements stored in a std::unordered_map container?
sobes.tech AI
Answer from AI
std::unordered_map in C++ is implemented as a hash table. Elements are stored in buckets, each of which contains a chain of elements with the same hash (usually a linked list or another container).
Key points of storage:
- Keys are hashed using a hash function (by default
std::hash<Key>). - The hash determines the index of the bucket where the element is placed.
- Elements in a bucket are stored as a list to resolve collisions.
- When adding an element, the hash is computed, the bucket is selected, and the element is added to the chain.
- When searching, the hash is first computed, the bucket is selected, and then the elements in the bucket are iterated to find the key.
This approach provides an amortized access time close to O(1), but the order of elements is not guaranteed and may change during rehashing.