2

我以这种方式定义了一张地图:

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();

这种行为的原因是什么?

4

1 回答 1

10

这是因为您使用副本循环。将循环更改为使用引用:

for(auto& mapElement : map){ ... }
于 2013-10-03T10:42:32.950 回答