Please read the new rule regarding the restriction on the use of AI tools. ×

Adding default values in a Map in C++ STL

Revision en1, by yash2040, 2020-04-14 13:59:57

Sometimes in map it is required that key which we have not assigned gets some default value. for ex- Write a cpp program to check whether 1 to 10 integer values exits in array or not

// for default values to map struct node { _ int value = -1;_ }; __ // driver function __ int main() { _ // Empty map container_ __ _ map<int, node> mp;_ __ _ int a[10] = { 1, 3, 4, 10, 7, 6, 5, 2, 11 };_ _ // Inserting elements in map_ _ // assigning 1 to values of array...by default they are -1_ __ _ for (int i = 0; i < 10; i++)_ _ mp[a[i]].value = 1;_ __ _ for (int i = 1; i <= 10; i++) {_ _ if (mp[i].value == -1)_ _ cout << i << " does not exist\n";_ _ }_ } Input : 1 3 4 10 7 6 5 2 11 Output :8 does not exist 9 does not exist

// for default values to map struct node { int value = -1; };

// driver function

int main() { // Empty map container map<int, int> mp1; cout << mp1[0] << "\n"; map<int, node> mp2; cout << mp2[0].value; } Run on IDE Output: 0 -1

So how does this work?? Primitive datatypes(Int, Char, Bool, Float etc) in CPP are undefined if not initialised, but in case of struct or Map they are initialised with some default values. So in above example we have created a user defined datatype struct with name node and assigned default value -1 to it. NOTE: By default map have default values but by using above method we can change it according to our need int — 0 float — 0 bool — 0

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above

Tags map, c++ stl

History

 
 
 
 
Revisions
 
 
  Rev. Lang. By When Δ Comment
en3 English yash2040 2020-04-14 14:21:50 239
en2 English yash2040 2020-04-14 14:09:51 1547
en1 English yash2040 2020-04-14 13:59:57 1740 Initial revision (published)