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:
- Declare a structure(say struct node) with a default value.
- 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:
// 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; } |
-1
Recommended Posts:
- Default Arguments in C++
- Default Methods in C++ with Examples
- Templates and Default Arguments
- C++ Internals | Default Constructors | Set 1
- Default arguments and virtual function
- Default Assignment Operator and References
- C++ default constructor | Built-in types
- Some Interesting facts about default arguments in C++
- Is body of a Default Constructor blank in C++?
- When does compiler create default and copy constructors in C++?
- Does C++ compiler create default constructor when we write our own?
- Count of all possible values of X such that A % X = B
- Number of values of b such that a = b + (a^b)
- Find the values of X and Y in the Given Equations
- How to traverse through all values for a given key in multimap?
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.

