How to Insert a Pair into an Unordered Map in C++?
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
// C++ program to insert a pair into an unordered map
#include <iostream>
#include <unordered_map>
using namespace std;
int main()
{
// declare an unordered map
unordered_map<int, string> mp
= { { 1, "Geek" }, { 2, "for" } };
// Create the pairs you want to insert
pair<int, string> pair3 = make_pair(3, "Geeks");
// Insert the pairs into the unordered map using
// insert() function
mp.insert(pair3);
// Print the unordered map
for (auto& pair : mp) {
cout << pair.first << ": " << pair.second << endl;
}
return 0;
}
// C++ program to insert a pair into an unordered map
using namespace std;
int main()
{
// declare an unordered map
unordered_map<int, string> mp
= { { 1, "Geek" }, { 2, "for" } };
// Create the pairs you want to insert
pair<int, string> pair3 = make_pair(3, "Geeks");
// Insert the pairs into the unordered map using
// insert() function
mp.insert(pair3);
// Print the unordered map
for (auto& pair : mp) {
cout << pair.first << ": " << pair.second << endl;
}
return 0;
}
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)