gpt4 book ai didi

c++ - 在迭代过程中是否会访问在std::unordered_set(或unordered_map)中添加的元素?

转载 作者:行者123 更新时间:2023-12-01 14:52:39 24 4
gpt4 key购买 nike

我有如下代码:

std::unordered_set<int> ht{1,2,3};
ht.reserve(10000); // ht will not exceed this size

for(int i = 0; i < n; i++)
{
auto j = i;
for(auto it = ht.begin(); it != ht.end(); ++it)
{
// do some stuff
int v = j++;
ht.emplace(v);
}
}


对于内部循环,我想从ht的开头到结尾进行循环,但是我不希望循环遍历循环中任何新添加的元素。换句话说,上面等同于下面吗?
std::unordered_set<int> ht{1,2,3};
ht.reserve(10000); // ht will not exceed this size

for(int i = 0; i < n; i++)
{
auto temp = ht;
auto j = i;
for(auto it = ht.begin(); it != ht.end(); ++it)
{
// do some stuff
auto v = j++;
temp.emplace(j);
}

ht = temp;
}


根据我所做的一些运行,这似乎是等效的,但是我不知道这是否是未定义的行为,或者它们是否确实等效。如果将 unordered_set更改为 vector,这将不起作用,但似乎前向迭代器可以工作。

如果不存在 ht.reserve(10000); // ht will not exceed this sizeht实际上超过了保留容量,答案是否会改变,因此所有转发迭代器都将无效?

最佳答案

不,这不安全:

On most cases, all iterators in the container remain valid after the insertion. The only exception being when the growth of the container forces a rehash. In this case, all iterators in the container are invalidated.



有时它可行,但我认为这对您来说还不够!

关于c++ - 在迭代过程中是否会访问在std::unordered_set(或unordered_map)中添加的元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61982129/

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