It' because you loop with copies. Change the loop to use references instead:
for(auto& mapElement : map){ ... }
Question
I defined a map in this way:
map<unsigned int, map<unsigned int, std::shared_ptr<MyObject>>> map;
The first map is preinitialized with some keys and empty maps (the inner maps).
I have a piece of code which operates with this map:
for(auto mapElement : map){
//cout << "1) " << mapElement.second.size() << endl;
if(mapElement.second.size()>0){
// do something
}
mapElement.second.clear();
cout << "2) " << mapElement.second.size() << endl;
}
for(auto mapElement : overwrittenMsgs){
cout << "3) " << mapElement.second.size() << endl;
}
This a possible output of one iteration:
1) 2
2) 0
1) 1
2) 0
3) 2
3) 1
So it seems that clear()
is not really working.
I can fix the problem by replacing mapElement.second.clear();
with map.at(mapElement.first).clear();
.
What's the reason of this behaviour?
Solution
It' because you loop with copies. Change the loop to use references instead:
for(auto& mapElement : map){ ... }