Open In App

How to Initialize Multimap with Default Values in C++?

Last Updated : 06 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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++




// C++ Program to illustrate how to initialize a multimap
// with default values
#include <iostream>
#include <map>
#include <vector>
using namespace std;
  
// custom data type
struct GFG {
    // member with default value
    int pointer = -1;
    // you can also initialize these members to defaalt
    // values using default constructor
};
  
int main()
{
    // Define keys and default value
    map<int, GFG> myMap;
  
    // creating pairs
    myMap[1], myMap[2], myMap[3];
  
    // Print the initialized map
    for (const auto& pair : myMap) {
        cout << pair.first << ": " << pair.second.pointer
             << endl;
    }
  
    return 0;
}


Output

1: -1
2: -1
3: -1

Time Complexity: O(N), where N is the size of the map.
Auxilliary Space: O(1), initialization does not cost any extra space.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads