How to Add Multiple Key-Value Pairs to a Map in C++?
Last Updated :
05 Mar, 2024
In C++, a map is a container that stores elements in key-value pairs, where each key is unique and associated with a value. In this article, we will learn how to add multiple key-value pairs to a map in C++.
Example:
Input:
myMap = { {1, "one"}
};
Elements to be insert = { {2, "two"}, {3, "three"}}
Output:
myMap = {{1, "one"}, {2, "two"}, {3, "three"}}
Map Multiple Key-Value Pairs in C++
To map multiple key-value pairs to a std::map in C++, we can use the std::map::insert function that inserts key-value pairs into the map. The insert function can take a pair, a range of pairs, or an initializer list of pairs. Here, we will insert the range of pairs defined in the initializer list.
C++ Program to Map Multiple Key-Value Pairs
C++
#include <iostream>
#include <map>
using namespace std;
int main()
{
map< int , string> myMap = { { 1, "one" } };
myMap.insert({ { 2, "two" }, { 3, "three" } });
cout << "Map after adding multiple key-value pairs:"
<< endl;
for ( const auto & pair : myMap) {
cout << pair.first << " => " << pair.second << endl;
}
return 0;
}
|
Output
Map after adding multiple key-value pairs:
1 => one
2 => two
3 => three
Time Complexity: O(M logN), where M is the number of new pairs and N is the size of the map.
Auxiliary Space: O(M)
Share your thoughts in the comments
Please Login to comment...