gpt4 book ai didi

c++ - 当我们迭代它时更改 HashMap 的行为是否已定义?

转载 作者:行者123 更新时间:2023-11-30 02:48:17 26 4
gpt4 key购买 nike

在带有 STL 的 C++ 中,可以在遍历 HashMap 时更改它吗?

显然,您可以更改迭代器变量本身(iter->first 和 iter->second),但是您可以:

  1. 更改迭代器不一定指向的现有键的值?

  2. 添加新 key ?

最佳答案

引自 cppreference's docs on 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.

因此更改与现有键关联的值是可以的,因为不会发生插入。使用 insert 显式插入或通过 operator[] 访问新 key ) 是不行的,因为它会导致重新散列并使所有迭代器无效。

Obviously, you can change the iterator variable itself (iter->first and iter->second)

这只是部分正确。您可以更改值,但不能更改 key ( iter->first )。这是因为 unordered_map<K,V>::value_type = pair<const K, V> .

关于c++ - 当我们迭代它时更改 HashMap 的行为是否已定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22102312/

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