Open In App

How to Insert Pairs into a Map in C++?

Last Updated : 29 Jan, 2024
Like Article

In C++, maps are STL containers that store key-value pairs and maintain the element’s order according to their keys. Pairs also store the data as key values. In this article, we will discuss how to insert a pair into a map in C++.

For Example,

map<int, string> mp = {(1, "geek"), (2,"for")}
pair<int, string> pr = {3, "geeks"}

Output: // after inserting pr to mp
mp = {(1, "geek"), (2,"for"), (3, "geeks")}

Insert Pair into a Map in C++

Pairs can be inserted directly into the map container by using the std::map::insert() function. We just need to pass the said pair as an argument to this function.

C++ Program to Insert Pair into a Map


// C++ program to demonstrate the insertion of pairs into
// map using insert() function.
#include <iostream>
#include <map>
using namespace std;
int main()
    // Step 1: Create a map with integer keys and string
    // values.
    map<int, string> myMap;
    // Step 2: Create a pair to insert.
    pair<int, string> newPair(25, "GeeksforGeeks");
    // Step 3: Insert the pair into the map using the
    // insert() function.
    // Iterate over the map and print each key-value pair.
    cout << "Contents of the map:" << endl;
    for (const auto& pair : myMap) {
        cout << "Key: " << pair.first
             << ", Value: " << pair.second << endl;
    return 0;


Contents of the map:
Key: 25, Value: GeeksforGeeks

We can also use std::map::emplace() method to insert pairs into a map instead of insert().

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads