Horje
How to Insert into Multimap using make_pair in C++?

In C++, a multimap is a container that stores key-value pairs in an ordered manner. Unlike a map, a multimap allows multiple values to be associated with a single key. In this article, we will learn how to insert into a multimap using make_pair in C++.

Example

Input: 
myMultimap = {{1, “C++”}, {2, “Java”}};
Pair to Insert: {1, “Python”};

Output:
myMultimap = {1, C++}, {1, Python}, {2, Java}

Insert into Multimap using make_pair in C++

The std::make_pair() function constructs a pair of the given type and returns this pair. We can use this function to create a pair and directly insert it into the multimap container using std::multimap::insert(). Note that the pair type and multimap type should be the same.

Syntax

multiMap.insert(make_pair(1, "apple"));

Where 1 is the key and “apple” is the associated value.

C++ Program to Insert into Multimap using make_pair

C++

// C++ Program to illustrate how to insert into a multimap
// using make_pair
#include <iostream>
#include <map>
using namespace std;
  
int main()
{
    // Initialize a multimap with some entries
    multimap<int, string> myMultimap
        = { { 1, "C++" }, { 2, "Java" } };
  
    // Insert a new pair into the multimap using make_pair
    myMultimap.insert(make_pair(1, "Python"));
  
    // Print the multimap after insertion
    for (auto& pair : myMultimap) {
        cout << "{" << pair.first << ", " << pair.second
             << "}, ";
    }
    cout << endl;
  
    return 0;
}

Output

{1, C++}, {1, Python}, {2, Java}, 

Time Complexity: O(logN) where N is the number of elements in the multimap.
Auxiliary Space: O(1)




Reffered: https://www.geeksforgeeks.org


C++

Related
Concatenate Two int Arrays into One Larger Array in C++ Concatenate Two int Arrays into One Larger Array in C++
How to Create a Stack of Multisets in C++? How to Create a Stack of Multisets in C++?
How to Create a Stack of Multimap in C++? How to Create a Stack of Multimap in C++?
How to Find the Size of a Dynamically Allocated Array in C++? How to Find the Size of a Dynamically Allocated Array in C++?
Custom Comparator for Multimap in C++ Custom Comparator for Multimap in C++

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
14