Open In App

How to Add Multiple Key-Value Pairs to a Map in C++?

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++ Program to illustrate how to insert multiple key
// value pairs in a map
#include <iostream>
#include <map>
using namespace std;
  
int main()
{
    // Creating a map
    map<int, string> myMap = { { 1, "one" } };
  
    // Adding multiple key-value pairs to the map
    myMap.insert({ { 2, "two" }, { 3, "three" } });
  
    // Printing the map after adding the key-value pairs
    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)

Article Tags :