Open In App
Related Articles

Default values in a Map in C++ STL

Improve Article
Save Article
Like Article

Prerequisite: Map in STL
A map is a container which is used to store a key-value pair. By default, In Primitive datatypes such as int, char, bool, float in C/C++ are undefined if variables are not initialized, But a Map is initially empty when it is declared. When this map is accessed with the [ ]  (e.g map<int,int> mpp;   mpp[1]; ) if the key is not present in the map , it gets added and its value is by default set to 0 (i.e value initialization gets invoked for the int) .To initialize the map with a random default value below is the approach:

  1. Declare a structure(say struct node) with a default value.
  2. Initialize Map with key mapped to struct node.


// For Structure 
struct Node {
   int value = -1;

// For Map with every key mapped to default value -1
Map < int, Node > M; 

Below is the illustration of the Map with a default value -1:


// C++ program to illustrate a Map
// initialize with default value
#include <bits/stdc++.h>
using namespace std;
// Structure Node
struct Node {
    int value = -1;
// Driver Code
int main()
    // Map initialize with key value
    // pair with each pair mapped with
    // structure Node
    map<int, Node> Map;
    // Print the default value of 1
    // store in Map
    cout << Map[1].value << endl;
    return 0;




Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!

Last Updated : 01 Jun, 2022
Like Article
Save Article
Similar Reads
Complete Tutorials