gpt4 book ai didi

c++ - 引用 unordered_map 中的值是否安全

转载 作者:行者123 更新时间:2023-12-01 14:09:31 29 4
gpt4 key购买 nike

例如:

#include <unordered_map>

class A{};
std::unordered_map<unsigned int, A> map {{0,{}},{1, {}},{2, {}}};

int main() {
A& a1 = map[1];
// some insert and remove operations ( key 1 never removed)
// ....
}

继续使用是否安全 a1在多次插入操作后,引用哪个键为“1”的值?

换句话说:
由于 std::vector 会在容量改变时移动元素,因此不能保证其元素的引用是有效的。这个事实是否也适用于 unordered_map ?

最佳答案

是的,这是安全的。从标准:

22.2.7 Unordered associative containers [unord.req]

The insert and emplace members shall not affect the validity of references to container elements, but may invalidate all iterators to the container. The erase members shall invalidate only iterators and references to the erased elements, and preserve the relative order of the elements that are not erased.



引用是安全的,但迭代器不是!

关于c++ - 引用 unordered_map 中的值是否安全,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62253972/

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