+ 1

Can we initialize unordered_map as global variable in c++?

I am trying to initialize unordered_map as global vairbale in c++ , but it is giving me error as my variable doesnot name a type when I do mp[0]='a'. How can we initialize unordered_map as an global variable in c++? https://code.sololearn.com/cwMg6mQpnn0L/?ref=app

7th Jul 2021, 1:14 PM
MahirShah
2 Respuestas
+ 12
The unordered_map can be declared as a global variable (or in this case, a global object), but the subsequent assignment steps has to happen within a function (as you are not declaring anything but rather assigning to an existing object). If this is not possible, just provide the values via constructor. unordered_map<int, char> mp{{0,'a'},{1,'b'}};
7th Jul 2021, 1:26 PM
Hatsy Rei
Hatsy Rei - avatar
0
yes we can, just declare unordered_map<whatever,whatever> map globally and for setting of parameters or data just make a funcion and call it. by this we can setting and using map as globally. ex-> unordered_map<string,pair<int,int>> um; ->make functions for setting data void f1(){ um["r"]={0,1}; um["l"]={0,-1}; um["u"]={-1,0}; um["d"]={1,0}; } ->using 1 time function call we can set data fun(); ->NOW YOU ARE READY TO USE YOUR MAP
31st Oct 2023, 7:36 PM
Mukesh Kumar Pathak