Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • C++
  • Standard Template Library
  • STL Vector
  • STL List
  • STL Set
  • STL Map
  • STL Stack
  • STL Queue
  • STL Priority Queue
  • STL Interview Questions
  • STL Cheatsheet
  • C++ Templates
  • C++ Functors
  • C++ Iterators
Open In App
Next Article:
Different Ways to Initialize an unordered_map in C++
Next article icon

Unordered Map in C++ STL

Last Updated : 03 Mar, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

In C++, unordered_map is an unordered associative container that stores data in the form of unique key-value pairs. But unlike map, unordered map stores its elements using hashing. This provides average constant-time complexity O(1) for search, insert, and delete operations but the elements are not sorted in any particular order.

Example:

C++
#include <iostream> #include <unordered_map> using namespace std;  int main() {          // Creating an unordered_map with integer     // keys and string values     unordered_map<int, string> um =     {{1, "Geeks"}, {2, "For"}, {3, "C++"}};      for (auto i : um)          cout << i.first << ": " << i.second         << endl;     return 0; } 

Output
3: C++ 1: Geeks 2: For 

Explanation: In this example, we created an unordered map um with three key-value pairs: {1, “Geeks”}, {2, “For”} and {3, “C++”}.

Syntax

Unordered map is defined as the std::unordered_map class template inside the <unordered_map> header file.

unordered_map<key_type, value_type> um;

where,

  • key_type: Data type of key.
  • value_type: Data type of value.
  • um: Named assigned to the unordered map.

Declaration and Initialization

We can declare and initialize unordered map in different ways as shown:

C++
#include <bits/stdc++.h> using namespace std;  void print(unordered_map<int, string> um){     for (auto i : um)         cout << i.first << " " << i.second          << endl; } int main() {          // Create an empty unordered_map     unordered_map<int, string> um1;          // Creating an unordered_map using     // initializer list     unordered_map<int, string> um2 =     {{1, "Geeks"}, {2, "For"}, {3, "C++"}};          print(um1);     cout << endl;     print(um2);     return 0; } 

Output
3 C++ 1 Geeks 2 For 

Explanation: In this example,

  • Statement unordered_map<int, string> um1 creates an empty unordered map. This is called default initialization.
  • Statement unordered_map<int, string> um2 = {{1, “Geeks”}, {2, “For”}, {3, “C++”}} initializes the unordered map using an initializer list.

Basic Operations

The basic operations on unordered map are shown below:

1. Inserting Elements

A new key-value pairs can be inserted in unordered map using either [] operator or insert() method. If the element with the given key already exists, the insert() method skip the insertion but [] operator updates the associated value to the new value.

Example:

C++
#include <bits/stdc++.h> using namespace std;  int main() {     unordered_map<int, string> um;          // Insert elements using square brackets     um[1] = "Geeks";          // Insert elements using insert() method     um.insert({2, "For"});     um.insert({3, "C++"});      for (auto i : um)          cout << i.first << ": " << i.second         << endl;     return 0; } 

Output
3: C++ 2: For 1: Geeks 

2. Accessing Elements

Elements in unordered map can be accessed using the [] operator or at() function. But if the key is not found, [] operator insert default value for key then return that default value. So, it is better to use at() method.

Example:

C++
#include <bits/stdc++.h> using namespace std;  int main() {     unordered_map<int, string> um =     {{1, "Geeks"}, {2, "For"}, {3, "C++"}};      // Access value associated with key 2     // using [] operator     cout << um[2] << endl;          // Access value associated with key 1     // using at() function     cout << um.at(1);     return 0; } 

Output
For Geeks

3. Updating Elements

In unordered map, elements can be updated by simply assigning a new value while accessing using assignment operator. But again with [] operator, a new element will be created if the key is not present.

Example:

C++
#include <bits/stdc++.h> using namespace std;  int main() {     unordered_map<int, string> um =     {{1, "Geeks"}, {2, "For"}, {3, "C++"}};      // Updating value associated with key 2     // using [] operator     um[2] = "By";     cout << um[2] << endl;          // Updating value associated with key 1     //using at() function     um.at(1) = "Tips";     cout << um.at(1);     return 0; } 

Output
By Tips

Explanation: In this example, the [] operator updates the value of key 2 to “By“, while the at() function updates the value of key 1 to “Tips“.

4. Finding Elements

Unordered map provides fast element search by key using the find() member function. This function returns iterator the element if found, otherwise returns end() iterator.

Example:

C++
#include <bits/stdc++.h> using namespace std;  int main() {     unordered_map<int, string> um =     {{1, "Geeks"}, {2, "For"}, {3, "C++"}};          // Finding element with key 2     auto it = um.find(2);          if (it != um.end())         cout << it->first << ": " << it->second;     else cout << "Not Found";     return 0; } 

Output
2: For

5. Traversing

Traversing an unordered map involves iterating through all the key-value pairs stored in the container. This can be done by incrementing begin() iterator till it is not equal to end() iterator.

Example:

C++
#include <bits/stdc++.h> using namespace std;  int main() {     unordered_map<int, string> um =     {{1, "Geeks"}, {2, "For"}, {3, "C++"}};      // Traversing using iterators with loop     for(auto it = um.begin(); it != um.end(); it++)         cout << it->first << ": " << it->second         << endl;     return 0; } 

Output
3: C++ 1: Geeks 2: For 

Range based for loop can also be used for simple traversal. Since unordered map does not maintain a specific order of elements, the order in which elements are traversed may not match the order in which they were inserted.

6. Deleting Elements

Elements in an unordered map can be deleted using the erase() function by passing a specific key or the iterator to the element.

C++
#include <bits/stdc++.h> using namespace std;  int main() {     unordered_map<int, string> um =     {{1, "Geeks"}, {2, "For"}, {3, "C++"}};          // Delete element which have key 2     um.erase(2);          // Delete first element     um.erase(um.begin());        for(auto it = um.begin(); it != um.end(); it++)         cout << it->first << ": " << it->second         << endl;     return 0; } 

Output
1: Geeks 

Explanation: In the above example, delete the pair that has the key 2 and also delete the first element pointed to by the iterator begin() using the erase() method.

Time Complexity

The below table lists the time complexity of the above operations on unordered map:

OperationTime Complexity
Insert an elementO(1) (average)
Delete an element by keyO(1) (average)

Access element by key

O(1) (average)

Find element by keyO(1) (average)
Update element by keyO(1) (average)
Traverse the mapO(n)

Other Common Operations

Unordered map is used in many situations for different purposes. The following examples’ aim is to help you master unordered map beyond the basics:

  • Find the Size of Unordered Map
  • Check if Unordered Map is Empty
  • Check if a Key is Present
  • Swap Two Unordered Map
  • Unordered Map for User Defined Datatype

Internal Working

In C++, unordered map provides the built-in implementation of hash table data structure. It hashes only the key from each element to find its index in the table and stores the element as key value pair. As it uses hashing, insertion, deletion and search operations take O(1) amortized time.

Unordered Map vs Map

Primary difference between unordered map and map is shown below:

  • Unordered Map does not maintain any specific order of elements. The order of elements is determined by their hash values, and it may vary.
  • Map stores elements in a sorted order based on the key. The elements are ordered according to a comparison function, typically in ascending order.

All Member Functions

Following is the list of all member functions of std::unordered_map class in C++:

Functions

Description

at()This function in C++ unordered map returns the reference to the value with the element as key k.

operator []

This operator is used to access or update the value of a specific key.

contains()

This function is used to check if the container contains element with specific key.

equal_range()

Return the bounds of a range that includes all the elements in the container with a key that compares equal to k

begin()Returns an iterator pointing to the first element in the container.
end()Returns an iterator pointing to the position beyond the last element in the container.

cbegin()

Return the constant iterator pointing to the first element in the container.

cend()

Returns a constant iterator pointing to the position beyond the last element in the container.

bucket()Returns the bucket number where the element with the key k is located in the unordered map.
bucket_count()Bucket count is used to count the total no. of buckets in the unordered map. No parameter is required to pass into this function
bucket_size()Returns the number of elements in each bucket of the unordered map.

max_bucket_count()

Return the maximum number which can hold by a bucket in the container.

count()Count the number of elements present in an unordered map with a given key.
find()Returns iterator to the element with specific key.
empty()Checks whether the unordered map is empty or not.

size()

Return the number of elements present inside the unordered map.

max_size()

Return the maximum number that which can hold by the unordered map.

erase()Erase elements from the unordered map container.

clear()

Delete all elements from the unordered map.

insert()

This function is used to insert an element into unordered map.

insert_range()

This function is used to insert range of elements into unordered map.

emplace()

This function is used to insert an element in the unordered map.

emplace_hint()

This function is used to insert a key with his value with a given hint.

swap()

This function is used to swap two unordered maps.

extract()

This function is used to extract the node from the unordered map.

merge()

This function is used to merge unordered maps into one.



Next Article
Different Ways to Initialize an unordered_map in C++

U

Utkarsh Trivedi
Improve
Article Tags :
  • C++
  • cpp-containers-library
  • CPP-Library
  • cpp-unordered_map
  • cpp-unordered_map-functions
  • STL
Practice Tags :
  • CPP
  • STL

Similar Reads

  • Unordered Map in C++ STL
    In C++, unordered_map is an unordered associative container that stores data in the form of unique key-value pairs. But unlike map, unordered map stores its elements using hashing. This provides average constant-time complexity O(1) for search, insert, and delete operations but the elements are not
    8 min read
  • Different Ways to Initialize an unordered_map in C++
    Initialization is the process of assigning the initial values to the std::unordered_map elements. In this article, we will learn different methods to initialize the std::unordered_map in C++. Table of Content Using Initializer ListBy Inserting Elements One by OneFrom Another std::unordered_mapFrom A
    3 min read
  • Commonly Used Methods

    • unordered_map begin() in C++
      The unordered_map::begin() is a built-in function in C++ STL which returns an iterator pointing to the first element in the unordered_map container or in any of its bucket. Syntax for first element in unordered_map container: unordered_map.begin() Parameters: This function does not accepts any param
      2 min read

    • unordered_map end( ) function in C++ STL
      The unordered_map::end() is a built-in function in C++ STL which returns an iterator pointing to the position past the last element in the container in the unordered_map container. In an unordered_map object, there is no guarantee that which specific element is considered its first element. But all
      3 min read

    • unordered_map size() in C++ STL
      The unordered_multimap::size() is a built-in function in C++ Standard Template Library which return's the number of element in the unordered map. Syntax: unordered_multimap_name.size() Return Value: It returns the number of the element present in the unordered map. Time complexity: Constant i.e. O(1
      1 min read

    • unordered_map insert in C++ STL
      The std::unordered_map::insert() in C++ STL is a built-in function used to insert a key-value pair in unordered_map container. As unordered maps only store unique elements, this function does not insert elements with duplicate keys. In this article, we will learn about std::unordered_map::insert() i
      5 min read

    • unordered_map at() in C++
      In C++, unordered_map at() is a library function used to find the value associated with a given key in the unordered_map container. Let's look at an example to see how to use this function. [GFGTABS] C++ #include <bits/stdc++.h> using namespace std; int main() { unordered_map<int, string
      2 min read

    • unordered_map find in C++ STL
      In C++, std::unordered_map::find function is used to search for a specific element using the key in an unordered map container. It is a member function of std::unordered_map container defined inside <unordered_map> header file. Syntaxum.find(key); Parameterskey: The key of the element to be se
      1 min read

    • unordered_map empty in C++ STL
      unordered_map::empty() function is used to check whether container size is zero or not. If container size is zero then it return TRUE otherwise it return FALSE. Syntax: unordered_map_name.empty() Parameters: This function does not accept any parameter Return type: This function returns boolean value
      2 min read

    Other Member Methods

    • unordered_map max_size in C++ STL
      The unordered_map::max_size is a built in function in C++ STL. It returns maximum number of elements which unordered_map can hold. Maximum number of elements in any container depends upon system and library implementation. Syntax size unordered_map.max_size() Parameters: It does not accept any param
      2 min read

    • unordered_map rehash in C++ STL
      The std::unordered_map::rehash() is a built in function C++ STL which sets the number of buckets in container to n or more. Syntax void rehash( size_type s );If s is greater than the current buckets into the container then rehashed is done. The new bucket count can be greater than or equal to n.If s
      2 min read

    • bucket_count and bucket_size in unordered_map in C++
      Unordered_map is an associated container that stores elements formed by the combination of key-value and a mapped value. The key value is used to uniquely identify the element and the mapped value is the content associated with the key. Both key and value can be of any type predefined or user-define
      4 min read

    • unordered_map bucket() in C++ STL
      The unordered_map::bucket() is a built-in STL function in C++ which returns the bucket number where the element with the key k is located in the map. Syntax: size_type bucket(key) Parameter: The function accepts one mandatory parameter key which specifies the key whose bucket number is to be returne
      1 min read

    • unordered_map load_factor in C++ STL
      The unordered_map::load_factor() is a built-in function in C++ STL which returns the current load factor in the unordered_map container. The load factor is the ratio between the number of elements in the container (its size) and the number of buckets (bucket_count): load_factor = size / bucket_count
      3 min read

  • Traversing a Map and unordered_map in C++ STL
    The maps are described as mapped associative containers for elements where each element has a key and value assigned to it. Another form of map container seen in the C++ STL is the unordered map. It is the same as map containers just that they don't store the data in sorted order. We can traverse ma
    6 min read
  • How to use unordered_map efficiently in C++
    Pre-requisite: unordered_set, unordered_map C++ provides std::unordered_set and std::unordered_map to be used as a hash set and hash map respectively. They perform insertion/deletion/access in constant average time. However, the worst-case complexity is O(n2).The reason is that the unordered_map sto
    6 min read
  • map vs unordered_map in C++
    Pre-requisite : std::map, std::unordered_mapWhen it comes to efficiency, there is a huge difference between maps and unordered maps. We must know the internal working of both to decide which one is to be used. Difference : | map | unordered_map -------------------------------------------------------
    2 min read
  • How to create an unordered_map of tuples in C++?
    Tuple - A tuple is an object that can hold a number of elements. The elements can be of different data types. The elements of tuples are initialized as arguments in the order in which they will be accessed. Unordered Map does not contain a hash function for a tuple. So if we want to hash a tuple the
    2 min read
  • How to create an unordered_map of user defined class in C++?
    unordered_map is used to implement hash tables. It stores key value pairs. For every key, a hash function is computed and value is stored at that hash entry. Hash functions for standard data types (int, char, string, ..) are predefined. How to use our own data types for implementing hash tables?unor
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences