std :: unordered_map指针/引用无效 [英] std::unordered_map pointers/reference invalidation

查看:434
本文介绍了std :: unordered_map指针/引用无效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

std::unordered_map<std::string, std::string> map;

map["k1"] = "v1";
auto& v1 = map["k1"];
map["k2"] = "v2";

阅读 http://en.cppreference.com/w/cpp/container/unordered_map


注释

Notes

交换功能不会使容器内的任何迭代器无效,但会使标记交换区域结束的迭代器无效。

The swap functions do not invalidate any of the iterators inside the container, but they do invalidate the iterator marking the end of the swap region.

即使删除了相应的迭代器,也只能通过删除该元素来使对存储在容器中的键或数据的引用和指针无效。

References and pointers to either key or data stored in the container are only invalidated by erasing that element, even when the corresponding iterator is invalidated.

在插入新值之后,即使在插入过程中可能会进行重新哈希处理,看起来也可以安全地使用 v1

It looks like v1 can be safely used after inserting new values, even if re-hashing might occur during insertion.

我对此报价的解释正确吗?修改地图后,是否可以使用地图中值的引用/指针(显然擦除值本身会使引用/指针无效)?

Is my interpretation of this quote correct? May I use references/pointers of the values from the map after modifying the map (obviously erasing the value itself would invalidate the reference/pointer)?

推荐答案


看起来 v1 可以插入新值后可以安全使用,即使在插入过程中可能发生重新哈希也是如此。

It looks like v1 can be safely used after inserting new values, even if re-hashing might occur during insertion.

是, std :: unordered_map :: operator [] 不会使引用无效,甚至会发生重新哈希。

Yes, std::unordered_map::operator[] doesn't invalidate references, even rehashing happens.

(强调我的)


如果发生插入并导致容器的重新哈希,则所有迭代器都是无效。否则,迭代器将不受影响。 引用没有无效

根据标准 [unord.req] / 9

(强调我的意思)


重新哈希将使迭代器无效,更改元素之间的顺序以及更改出现在存储桶中的元素,但不会使对元素的指针或引用无效

这篇关于std :: unordered_map指针/引用无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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