What Are Unordered Containers?
Unordered containers in C++ are a family of data structures that store elements in an unordered manner, meaning the sequence of elements is not preserved. This lacks of order is compensated by faster access times compared to ordered containers like std::set
or std::map
. The key advantage of unordered containers lies in their average constant time complexity for common operations such as insertion, deletion, and retrieval. Unordered containers in STL provide a hash-based alternative to the ordered containers like sets and maps. Unlike ordered containers that maintain a sorted order, unordered containers use hash functions to achieve faster average access time for search, insertion, and deletion operations.
The key unordered containers in C++ are:
std::unordered_set
: A set that contains unique elements in no particular order.std::unordered_map
: A map that associated unique keys with values in no particular order.std::unordered_multiset
: Similar tostd::unordered_set
, but allows duplicate elements.std::unordered_multimap
: Similar tostd::unordered_map
, but allows duplicate keys.
Characteristics:
Hashing Mechanism:
Unordered containers rely on a hash function to map elements to unique indices within the container. This hash function is responsible for ensuring efficient access and retrieval. When an element is inserted, the hash function calculated its hash value, determining the position within the container.
No Sorting Overhead:
Unlike ordered containers, unordered containers do not impose any sorting overhead. This makes them suitable for scenarios where the order of elements is not a primary concern.
Fast Average Time Complexity:
The average time complexity for insertion, deletion, and retrieval operations in unordered containers is O(1). This constant time complexity is achieved through the use of hash tables.
Anatomy of std::unordered_set
It is designed to store unique elements in no specific ordered. The uniquenesss of element is maintained by employing hashing techniques, ensuring that no two elements in the set have the same value.
Characteristics