unordered_map C++

Learn via video course
FREE
View all courses
C++ Course: Learn the Essentials
C++ Course: Learn the Essentials
by Prateek Narang
1000
5
Start Learning
C++ Course: Learn the Essentials
C++ Course: Learn the Essentials
by Prateek Narang
1000
5
Start Learning
Topics Covered

Introduction

unordered_map is a data structure capable of storing data in the form of keys value pairs. It uses a hashing function to store a key-value pair, due to which the average time complexity for searching a key-value pair becomes O(1).

Syntax

In order to create an unordered_map in C++, we can use the following syntax.

Here, datatype1 is the data type of the keys and datatype2 is the data type of the values of the corresponding keys. The map_name is the name of the unordered_map variable.

For example, if we want to create an unordered_map with its key as an integer value and the value of the corresponding key has a string datatype, then it will look like this:

Example of an Unordered_Map in C++

In C++, if we want to create an unordered_map with the data type of key as datatype1 and the data type of the mapped values of the keys as datatype2, then we use the following syntax.

Output

Unordered_map Vs Map

Featureunordered_mapmap
Order of ElementsNo specific order of elements.Elements are stored in ascending order based on keys.
Data StructureUses a hash table (unordered).Uses a balanced binary search tree (ordered).
Order MaintenanceDoes not maintain order between elements.Maintains order based on keys.
Time ComplexityAverage Case O(1) for most operations.O(log n) for most operations.
Lookup (find) Time ComplexityO(1) average case.O(log n) average case.
Insertion and Deletion Time ComplexityO(1) average case.O(log n) average case.
Memory OverheadTypically lower memory overhead.Slightly higher memory overhead due to balanced tree structure.
DuplicatesDoes not allow duplicate keys.Does not allow duplicate keys.
Custom SortingNo custom sorting options.Allows custom sorting via comparators.
Use CasesSuitable for unordered data storage and quick access.Suitable when elements need to be sorted or when custom ordering is required.

Unordered_map Vs Unordered_set

Featureunordered_mapunordered_set
Element TypeKey-value pairs (elements with associated values).Elements (no associated values, used for presence/absence checks).
UsageUsed to store and retrieve key-value pairs.Used to check for the presence or absence of elements.
Operator [] for Value AccessAllows access to the associated value using keys.Not applicable; no values associated with elements.
Element SearchUses keys to search for elements.Uses the find() function to search for elements.
Duplicate ElementsDoes not allow duplicate keys (keys must be unique).Automatically enforces uniqueness of elements.
Memory OverheadHigher memory overhead due to key-value pairs.Lower memory overhead as it only stores elements.
Example Use CasesStoring data with associated values, e.g., dictionaries.Checking for the presence of items, e.g., set operations.

Methods of unordered_map in C++

1. Member Functions

Some of the most commonly used member functions are discussed below.

Member FunctionDescriptionExample
= OperatorAssign elements from one map to anotherunordered_map<datatype1, datatype2> map_name_1 = map_name_2;
empty()Check if the map is emptybool is_empty = map_name.empty();
size()Get the number of key-value pairsint map_size = map_name.size();
max_size()Get the maximum storage capacityint max_capacity = map_name.max_size();
begin()Get an iterator to the first elementauto map_begin = map_name.begin();
end()Get an iterator to the endauto map_end = map_name.end();
cbegin()Get a constant iterator to the beginningauto map_begin = map_name.cbegin();
cend()Get a constant iterator to the endauto map_end = map_name.cend();
[] OperatorAccess an element by keydata_type mapped_value = map_name[k];
at()Access an element by key with bounds checkingdata_type mapped_value = map_name.at(k);
find()Find an element by keyauto itr = map_name.find(k);
count()Count the occurrences of a keyint count_k = map_name.count(k);
equal_range()Get a range of elements by keyauto itr = map_name.equal_range(k);
insert()Insert a key-value pairmap_name.insert({key, value});
emplace()Insert a key-value pair efficientlymap_name.emplace(key, value);
erase()Erase an element by iterator or keymap_name.erase(itr); or map_name.erase(k);
clear()Erase all elements in the mapmap_name.clear();

2. Non-member Function Overloads

  • Operators
    There are two operators in unordered_map. These two operators are discussed below.
  1. Equality operator (==) Two unordered_maps (map_name1 and map_name2) satisfy the equality operator (map_name1 == map_name2) if both the unordered_maps have the same sizes and all the key-value pairs that are present in both the unordered_maps are the same.
  2. Inequality operator (!=) Two unordered_maps (map_name1 and map_name2) satisfy the inequality operator (map_name1!=map_name2) if either both of the maps have different sizes or there exists at least one key-value pair that is present in one of the unordered_map and not in the other.
  • Swap
    This function is used to swap the entire contents of one unordered_map with the other unordered_map.

Time Complexity for Insertion, Deletion, and Update in unordered_map in C++

An unordered_map offers three commonly used operations: insertion, deletion, and updation.

  • Insertion: To insert a key 'k' and its value v into an unordered_map, you can use various syntax forms. The best and average case time complexity for insertion is O(1), while the worst case time complexity is O(n).

  • Deletion: Removing an element with key k from an unordered_map is accomplished with the erase method. The best and average case time complexity for deletion is O(1), with a worst-case time complexity of O(n).

  • Updation: Updating the value associated with a key to new_value can be done with simple assignment. The best and average case time complexity for updating is O(1), while the worst case time complexity is O(n).

Note: In all three operations, i.e., insertion, deletion, and updation, the best case scenario takes place when the hash function of the unordered_map is good and there are a minimal number of collisions that take place at respective operations. In contrast, the worst scenario takes place when the hash table of the unordered_map is not good, and a very high number of collisions occur at each operation.

C++ Unordered_map Class Template Parameters

An unordered_map in c++ is defined as follows.

Hence, it contains 5 class template parameters that are individually discussed below.

  1. Key - This parameter defines the data type of the key values present in the unordered_map.

  2. T - This parameter defines the data type of the keys' mapped values present in the unordered_map.

  3. Hash - In unordered_map, each key is provided with a unique value. This unique value is used to perform insertion, deletion, and the updation operation in an unordered_map.

  4. Pred - This parameter is a binary predicate that takes two values, a, and b, as input and returns a boolean value as an output. a and b have their data types the same as the data type of the key. By default, the Pred is set to equal_to, which means that the predicate returns true if a is equal to b. If a is not equal to b, it returns false. This parameter is useful when we have to search for a key or update the mapped value of the key in an unordered_map.

  5. Alloc - This parameter defines how the memory is allocated when we want to insert a new key-value pair in an unordered_map. By default, Alloc uses an allocator class that allocates memory independent of what we insert in the unordered_map.

Member Types

The unordered_map class contains several data members/member types in the table below.

Member TypeDefinitionDefault Parameter
key_typeThis defines the key's data type, i.e., the first parameter of the class template.
mapped_typeThis defines the datatype of mapped values, i.e., the second parameter of the class template.
value_typeThis defines data type of the key-value pair (i.e. pair<key_type,map_type>)
hasherThis defines the hash function i.e. the third parameter of the class template.hash<key_type>
key_equalThis defines the Pred i.e. fourth parameter of the class template.equal_to<key_type>
allocator_typeThis defines the Alloc i.e. fifth parameter of the class template.allocator<value_type>
referenceThis defines the pointer to the key-value pair in the unordered_map.
const_referenceThis defines the constant pointer to the key-value pair in the unordered_map.
pointerThis defines the pointer used by the allocator.value_type*
const_pointerThis defines the constant pointer used by the allocator.const value_type*
iteratorThis defines the iterator to iterate through the key-value pairs inside the unordered_map.
const_iteratorThis defines the iterator to iterate through the constant key-value pairs inside the unordered_map.
local_iteratorThis defines the local iterator to iterate through the key-value pairs inside the unordered_map.
const_local_iteratorThis defines the local iterator to iterate through the constant key-value pairs inside the unordered_map.
size_typeThis is an unsigned int value that keeps track of the size of the unordered_map.usually the same as size_t
difference_typeThis is a signed integral data member.usually the same as ptrdiff_t

Container Properties of Unordered_map in C++

The key-value pairs present inside the unordered_map container following five properties.

  1. Associative: Unordered maps use key-based access, ensuring efficient value retrieval by key, irrespective of the key-value pair's position.

  2. Unordered: Data inside an unordered_map lacks a specific order, allowing for swift average-case access without any predetermined sequence.

  3. Mapping: Unordered maps establish a direct link between keys and values, streamlining key-based lookups and value retrieval.

  4. Unique Keys: Unordered maps enforce key uniqueness, eliminating ambiguity by preventing duplicate keys in the container.

  5. Allocator Aware: Unordered maps utilize allocators for flexible memory management, optimizing memory allocation and deallocation strategies for efficient storage handling.

Conclusion

  1. Unordered_map: Stores data as key-value pairs.
  2. Time complexity: Best and average cases are O(1), worst case is O(n).
  3. Unordered_map vs. Unordered_set: Maps have key-value pairs, sets store individual values.
  4. Unordered_map vs. Map: Unordered_map is unordered, Map is sorted.
  5. Implementation: Unordered_map uses a hash table, Map uses a Red-Black tree.