Default values in a Map in C++ STL

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 in a Map, every key is mapped with default value zero when the map is declared. To initialize the map with a random default value below is the approach:

Approach:



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

Syntax:

// 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:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to illustrate a Map
// initialise with default value
#include <bits/stdc++.h>
using namespace std;
  
// Structure Node
struct Node {
    int value = -1;
};
  
// Driver Code
int main()
{
    // Map initialise 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;
}

chevron_right


Output:

-1

competitive-programming-img

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :
Practice Tags :


7


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.