The behavior of the code below surprises me:
map<string,long>* map_ptr;
if(true){
map<string, long> my_map;
my_map["a"] = 1;
my_map["b"] = 2;
my_map["c"] = 3;
map_ptr = &my_map;
}
//works ONLY IF this for loop comes before the next for loop
for(map<string, long>::iterator itr = map_ptr->begin(); itr != map_ptr->end(); ++itr)
cout << itr->second << endl;
// does not work prints random bits
for(map<string, long>::iterator itr = map_ptr->begin(); itr != map_ptr->end(); ++itr)
cout << itr->first << endl;
I knew variables created within if statement only have scope within it, but I thought declaring a pointer to them will work. I have limited knowledge about the stack structure of this code, but I thought the variables, though out of scope, are still on the stack so they still exist. But it seems there's more happening than I know of. What surprised me the most is why the first for loop prints out things correctly, but only if it is executed before the second for loop. I guess it has something to do with the type because long
is built-in where as string
is not, but this is far from sufficing to explain to what's going on.
Please help me understand this code. Thanks!