In C++, a map is an associative container that stores the elements as key-value pairs where each element has a key and a mapped value. In this article, we will learn how to add elements to a map in C++ STL.
For Example,
Input: myMap = {{1, "Ram"}, {2, "Mohit"}}; Output: myMap = {{1, "Ram"}, {2, "Mohit"}, {3: "Sam"}};
Add Elements into a Map in C++
To insert a key-value pair in a std::map, we can use the array subscript operator [] with the key inside the brackets and assign it the required value using the assignment operator. If the key already exists, then its value will be updated. Otherwise, the new elements will be added
C++ Program to Add Key-Value Pair into a Map
The below example demonstrates how we use insert() function to add key-value pair into a map in C++ STL.
// C++ program to add key-value pair in map in STL #include <iostream> #include <map> using namespace std;
int main()
{ // Create a map
map< int , string> myMap;
// Insert key-value pairs into the map
myMap[1] = "Apple" ;
myMap[2] = "Banana" ;
myMap[3] = "Cherry" ;
// Print the map
cout << "The map is: \n" ;
for ( const auto & pair : myMap) {
cout << pair.first << ": " << pair.second << "\n" ;
}
return 0;
} |
The map is: 1: Apple 2: Banana 3: Cherry
Time Complexity: O(m log n), where n is the number of elements in the map, and m is the number of elements to be inserted.
Auxiliary Space: O(m)
Note: We can also use map::insert()ethod to add key-value pairs in a map in C++.