How to Initialize Multimap with Default Values in C++?
Last Updated :
06 Mar, 2024
In C++, a multimap is a container provided by the STL library 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 initialize a multimap with default values in C++.
Initialize Multimap with Default Values in C++
In C++ STL, multimap values are automatically initialized the moment their key is referred for built-in data types. For example, if the type of the value is int, it will be automatically initialized to 0 when the pair is created.
If we want to initialize the custom data type value to default values in a multimap, we can define the default values in the data type declaration itself and they will be automatically assigned these values in the multimap.
C++ Program to Initialize Multimap with Default Values
The below example demonstrates how we can initialize a multimap with default values in C++.
C++
#include <iostream>
#include <map>
#include <vector>
using namespace std;
struct GFG {
int pointer = -1;
};
int main()
{
map< int , GFG> myMap;
myMap[1], myMap[2], myMap[3];
for ( const auto & pair : myMap) {
cout << pair.first << ": " << pair.second.pointer
<< endl;
}
return 0;
}
|
Time Complexity: O(N), where N is the size of the map.
Auxilliary Space: O(1), initialization does not cost any extra space.
Share your thoughts in the comments
Please Login to comment...