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

(强调我的意思)


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