How to Insert Pairs into a Map in C++?
Last Updated :
29 Jan, 2024
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,
Input:
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++
#include <iostream>
#include <map>
using namespace std;
int main()
{
map< int , string> myMap;
pair< int , string> newPair(25, "GeeksforGeeks" );
myMap.insert(newPair);
cout << "Contents of the map:" << endl;
for ( const auto & pair : myMap) {
cout << "Key: " << pair.first
<< ", Value: " << pair.second << endl;
}
return 0;
}
|
Output
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().
Share your thoughts in the comments
Please Login to comment...