Open In App

How to Insert a Pair into an Unordered Map in C++?

Last Updated : 13 Feb, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In C++, STL provides the pair container which allows the user to store two objects that can be of the same or different type as a single unit. On the other hand, the Unordered Map is a data structure that stores the data in the form of key-value pairs where the keys must be unique. In this article, we will learn how we can insert a Pair into an Unordered Map in C++.

Example:

Input: 
myUnorderedMap = { {1,"Geek"}, {2, "for"} }
Output:
myUnorderedMap= { {1,"Geek"}, {2, "for"}, {3,"Geeks"} }
// pairs inserted into the unordered map

Insert a Pair into an Unordered Map in C++

To insert a std::pair into a std::unordered map in C++, we can simply use the std::unordered_map::insert() method to insert the pair into the unordered map. It is a member function of the std::unordered_map class and only need to pass the said pair as an argument to it.

Note: We must ensure the pair data type matches with the data type of the unordered map.

C++ Program to Insert a Pair into an Unordered Map


Output
3: Geeks
2: for
1: Geek

Time Complexity: O(1), worst case O(n), where n is the number of elements in the unordered_pair
Auxilary Space: O(1)


Next Article
Practice Tags :

Similar Reads