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

标签 c++ for-loop unordered-set

我有如下代码:

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/

相关文章:

c++ - 获取被调用函数的行号

python - 如何使Python中的for循环更快?

java - 从Java中的for循环内部返回的正确方法?

python - 嵌套循环中结果的唯一变量名称

c++ - 如何在 C++ 中更有效地生成这么多排列?

c++ - 在无序字符串集中查找字符串的时间复杂度

c++ - OpenGL glCreateProgram() 总是返回 1 并删除之前的程序

c++ - 使用QMediaPlayer时出现"QWidget::paintEngine: Should no longer be called"

c++ - 在 c++/c++11 中测试 "POD-ness"?

c++ - 使用插入 C++ 后维护无序集中的顺序