Table of contents
1.
Syntax Unordered_Map in C++
2.
Examples of Unordered_Map in C++
2.1.
C++
3.
Create C++ STL unordered_map
3.1.
C++
4.
How to Initialize an Unordered_Map in C++?
5.
Methods on unordered_map
6.
Difference Between unordered_map and unordered_set
7.
Frequently Asked Questions
7.1.
In C++, which map is faster?
7.2.
Why is it called Unordered_map?
7.3.
What does Unordered_map return in C++?
7.4.
What does the count() method do in terms of unordered_map in C++?
7.5.
What is the difference between map and unordered_map in C++?
8.
Conclusion
Last Updated: Sep 6, 2024
Easy

Unordered_map In C++

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Unordered_map In C++ is a dictionary-type data structure that stores elements. An unordered map has a (key, value) pair sequence that quickly retrieves individual elements based on their unique key.

Unordered_map In C++

Each unique key has just one value associated with it, and key-value is commonly used to identify an element uniquely. It is also known as an associative array. The mapped value in a (key, value) pair is an object linked with each unique key. The type of key and mapped value for each pair may be different.

The elements in an unordered map are not sorted in any specific order based on their key-value or mapped value. 

Instead, it groups things into buckets based on their hash values, allowing for quick access to individual elements via their key values.

Note: Its time complexity can range from O(1) to O(n^2) in the worst-case, especially for large prime numbers. To avoid a TLE mistake, in this case, it is highly recommended that you use a map instead.

Syntax Unordered_Map in C++

The following is the syntax of unordered_map in C++ STL

unordered_map<key_datatype, mapped_datatype> map_name;

Examples of Unordered_Map in C++

Example 1 - An example of a C++ program for counting the frequency of elements in an array

Code:

  • C++

C++

#include <iostream>
#include<unordered_map>
using namespace std;

int main()
{
   int arr[]={2,3,3,4,2,4,1,1,2,6,5,5};
  
   //calculating the length of the array
   int n=sizeof(arr)/sizeof(arr[0]);
  
   //creating the unordered_map map named umap
   unordered_map<int,int> umap;     
   for(int i=0;i<n;i++){
       umap[arr[i]]++;
   }
  
   //printing the element with their count frequency
   for(auto it: umap){
       cout<<"Element: "<<it.first<<"  "<<"Freq: "<<it.second<<endl;
   }
   
   return 0;
}
You can also try this code with Online C++ Compiler
Run Code

Output

Element: 5  Freq: 2

Element: 6  Freq: 1

Element: 1  Freq: 2

Element: 4  Freq: 2

Element: 3  Freq: 2

Element: 2  Freq: 3

You can also compile this code with the help of Online C++ Compiler

Example 2- Let’s take another example to understand unordered_map clearly. Suppose there is a string of words, and you have to find frequencies of individual words.

Code:

Output

(Coding Ninjas Studio, 1)

(on, 1)

(for, 1)

(time, 1)

(practice, 1)

(ninjas, 1)

(quiz, 2)

Create C++ STL unordered_map

An unordered_map in C++ is a container that stores key-value pairs in a hash table. It provides constant-time average complexity for insertions, deletions, and lookups, making it efficient for storing and accessing data.

Code:

  • C++

C++

#include <iostream>
#include <unordered_map>

int main() {
std::unordered_map<std::string, int> myMap;
myMap["apple"] = 5;
myMap["banana"] = 3;

std::cout << "Value of apple: " << myMap["apple"] << std::endl;
std::cout << "Value of banana: " << myMap["banana"] << std::endl;

return 0;
}
You can also try this code with Online C++ Compiler
Run Code

Output:

Value of apple: 5
Value of banana: 3

Explanation:

  • We include the <unordered_map> header to use the unordered_map container.
  • We declare an unordered_map named myMap with key type std::string and value type int.
  • We insert key-value pairs into the map using the [] operator.
  • We access the values using the same [] operator.

How to Initialize an Unordered_Map in C++?

An unordered_map in C++ can be initialized using various methods like assignment, initializer list, or pair-wise insertion. Initialization can be done during declaration or later in the code.

Code:

#include <iostream>
#include <unordered_map>

int main() {
    // Initialization during declaration
    std::unordered_map<std::string, int> myMap = {{"apple", 5}, {"banana", 3}};

    // Later initialization
    std::unordered_map<int, std::string> anotherMap;
    anotherMap[1] = "one";
    anotherMap[2] = "two";

    return 0;
}

Explanation:

  • During declaration, we can initialize an unordered_map using brace-enclosed initializer lists.
  • For later initialization, we declare an empty unordered_map and insert key-value pairs using the [] operator.

Methods on unordered_map

Internally, the C++11 library contains functions to see bucket count, bucket size and the used hash function and various hash policies. However, these are less useful in real-world applications.

Iterator can iterate over all elements of the unordered map.

The unordered_map has the following methods:

Method Description
at() It returns a reference to the value with the element k as the key in the C++ unordered map.
begin() It returns an iterator referring to the first element in the container in the unordered_map container.
bucket() It returns the bucket number in the map where the element with the key k is found.
bucket_count() It counts the total number of buckets in the unordered map.
bucket_size() It returns the number of entries in the unordered map's buckets.
count() It counts the number of entries in an unordered map with a given key.
equal_range() It gives the bounds of a range containing all elements with a key that compares to k.
find() It returns an iterator to the element found by the find() function.
empty() It checks whether the container is empty in the unordered_map container.
erase() It deletes elements from the unordered map container using the erase() function.

This concludes our topic of unordered_map in C++. Now let’s move on to the FAQ section.

Must Read Dynamic Binding in C++

Difference Between unordered_map and unordered_set

Feature unordered_map unordered_set
Container Type Stores key-value pairs (associative container) Stores unique elements (set container)
Usage Used to map keys to values Used to store unique values
Key-Value Relationship Each element is a pair consisting of a key and its associated value Each element is a single value
Access Access elements using keys Access elements directly
Complexity Average case: O(1) for insertion, deletion, and lookup Average case: O(1) for insertion, deletion, and lookup
Duplication Keys are unique, values can be duplicated Elements are unique, no duplicates allowed
Iterator Behavior Iterators point to pairs (key-value) Iterators point to elements
Memory Consumption Typically consumes more memory than unordered_set due to storing both keys and values Typically consumes less memory than unordered_map since only stores single elements

The major difference between an unordered map and an unordered set is that an unordered set does not support key values. In an unordered set, there is only one key. On the other hand, an unordered map has both a key and a value. If there is a situation where you have to count the individual frequencies of each tuple in a set, you will have to use the unordered map as the unordered set does not support it.

Frequently Asked Questions

In C++, which map is faster?

The unordered map is the fastest in C++ in most cases. In some circumstances, though, the map is speedier.

Why is it called Unordered_map?

It is called Unordered_map because the items in this map are kept in random order. The keys are not stored in any particular order, hence the name.

What does Unordered_map return in C++?

It returns a reference to the value mapped to a key that is equivalent to that key.

What does the count() method do in terms of unordered_map in C++?

In terms of unordered_map in C++, the count() method returns the number of elements with a specific key in the unordered_map container. It checks whether the container contains an element with the given key and returns either 0 (if not found) or 1 (if found).

What is the difference between map and unordered_map in C++?

The main difference between map and unordered_map in C++ is that map is a sorted associative container that stores key-value pairs, maintaining order based on the keys' comparison, while unordered_map is a hash table-based container that provides constant-time average complexity for insertions, deletions, and lookups.

Conclusion

In this article, we have extensively discussed the unordered map in C++ language and how we can use it in our program. We learned the syntax of unordered_map and its implementation with multiple examples. We learned the difference between unordered_map and unordered_set. We also learned the various methods of unordered_map.

Also, check out this article - 

We hope that this blog has helped you enhance your knowledge regarding unordered maps in C++ STL(Standard Template Library), and if you would like to learn more, check out our articles in the Code360 library.

Live masterclass