gpt4 book ai didi

c++ - std::unordered_map 指针/引用失效

转载 作者:可可西里 更新时间:2023-11-01 16:06:25 24 4
gpt4 key购买 nike

我有以下代码:

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 可以在插入新值后安全使用,即使在插入过程中可能会发生重新散列。

我对这句话的解释正确吗?我可以在修改 map 后使用 map 中值的引用/指针吗(显然删除值本身会使引用/指针无效)?

最佳答案

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

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

(强调我的)

If an insertion occurs and results in a rehashing of the container, all iterators are invalidated. Otherwise iterators are not affected. References are not invalidated.

来自标准,[unord.req]/9 :

(强调我的)

Rehashing invalidates iterators, changes ordering between elements, and changes which buckets elements appear in, but does not invalidate pointers or references to elements.

关于c++ - std::unordered_map 指针/引用失效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39868640/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com