[英]STD Map clear() strange behaviour
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. 所以似乎
clear()
并没有真正起作用。
I can fix the problem by replacing mapElement.second.clear();
我可以通过替换
mapElement.second.clear();
来解决这个问题mapElement.second.clear();
with map.at(mapElement.first).clear();
with
map.at(mapElement.first).clear();
. 。
What's the reason of this behaviour? 这种行为的原因是什么?
It' because you loop with copies . 它'因为你循环复制 。 Change the loop to use references instead:
更改循环以使用引用:
for(auto& mapElement : map){ ... }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.