C ++存储对std :: map中的值的引用 [英] C++ Storing references to values in std::map

查看:560
本文介绍了C ++存储对std :: map中的值的引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以假设添加/删除元素到std :: map不会影响其他元素(即使它们被重新定位在内存中),所以下面是安全的:

Am I right in assuming that adding/removing elements to an std::map does not effect the other elements (ie cause them to be relocated in memory) and so that the following is safe:

我查看了容器上的信息的各种网站,但只发现了迭代器无效的情况,我已经知道了...

I looked at various sites with info on the container but only found out about the cases where iterators are invalidated, which I already know...

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上测试了一些类似的代码似乎工作,但这并不意味着我不只是幸运,或者它不会改变编译器。

I tested some similar code on VC9, which seems to work however that doesn't mean I didn't just get lucky or that it doesn't vary across compilers.

推荐答案

23.1.2 / 8 关于关联容器


插入成员不应影响迭代器和对容器的引用的有效性,并且擦除成员应仅使迭代器和对已删除元素的引用无效。

The insert members shall not affect the validity of iterators and references to the container, and the erase members shall invalidate only iterators and references to the erased elements.

这篇关于C ++存储对std :: map中的值的引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆