我以这种方式定义了地图:
map<unsigned int, map<unsigned int, std::shared_ptr<MyObject>>> 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;
}
这可能是一次迭代的输出:
1) 2
2) 0
1) 1
2) 0
3) 2
3) 1
因此,这似乎clear()
并没有真正起作用。
我可以通过替换mapElement.second.clear();
为来解决此问题map.at(mapElement.first).clear();
。
这种行为的原因是什么?
这是因为您循环复制。更改循环以改为使用引用:
for(auto& mapElement : map){ ... }
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句