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

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

我对这句话的解释正确吗?我可以在修改 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/

相关文章:

vba - 自身进行变量迭代-不同类型的不同行为

C++ 嵌套循环没有给我任何值

c++ - 类的 begin() 方法编译错误

c++ - 为自定义类和库类实现通用接口(interface)的最佳方法

c++ - 我们可以使用 std::vector 定义一个固定宽度的二维矩阵吗?

c++ - 使用 json c++ 的输出在字段中获取奇怪的字符

c++ - 您可以将 "this"静态转换为基类构造函数中的派生类,然后稍后使用结果吗?

c++ - Worker/Controller 多线程和接口(interface)类

c++ - 通过 operator[] 和 .at() 访问 vector 的负索引

c++ - 内联 constexpr 函数定义是否合法? gcc (ok) vs clang (error)