我理解的是否正确:在std::map中添加/删除元素不会影响其他元素(即不会导致它们在内存中重新定位),因此以下操作是安全的:
我查看了各种包含有关容器信息的网站,但只发现了迭代器无效的情况,这已经是我知道的了...
std::map<std::string,std::string> map;
PopulateMap(map);
std::string &a= map["x"];
AddMoreData(map);
RemoveRandomKeysExceptX(map);
map["x"] = "foo";
std::cout << a << " " << map["x"] << std::endl;//prints "foo foo"
a = "bar";
std::cout << a << " " << map["x"] << std::endl;//prints "bar bar"
我在 VC9 上测试了一些类似的代码,看起来可以工作,但这并不意味着我只是运气好或者它在不同的编译器上表现不同。