c++ - 这是正确的行为吗? std::map 迭代器失效

标签 c++ iterator stdmap

#include <iostream>
#include <map>

int main(int argc, char** argv)
{
  std::map<int, int> map;
  map.emplace(1, 1);
  auto reverse_iter = map.rbegin();
  std::cout << reverse_iter->first << ", " << reverse_iter->second << std::endl;
  map.emplace(2, 2);
  std::cout << reverse_iter->first << ", " << reverse_iter->second << std::endl;

  return 0;
}

打印出来:

1, 1
2, 2

根据标准,这真的应该发生吗?我没有接触 reverse_iter 但它指向的值正在改变。我认为 std::map 中的迭代器应该可以安全地防止插入。然而,它似乎决定 reverse_iter 不再指向我告诉它的值,而是指向“此时 map 末尾发生的任何事情”。

更新:更多信息,以防万一:前向迭代器似乎不会发生这种情况(在我似乎能找到的任何情况下),我的 gcc 版本是 5.1.1-4。

最佳答案

根据 C++ 标准(23.2.4 关联容器)

9 The insert and emplace members shall not affect the validity of iterators and references to the container, and the erase members shall invalidate only iterators and references to the erased elements.

另一方面(24.5.1 反向迭代器)

1 Class template reverse_iterator is an iterator adaptor that iterates from the end of the sequence defined by its underlying iterator to the beginning of that sequence.

虽然在最后引用中提到了类 std::reverse_iterator,但对于标准容器的反向迭代器同样有效。

根据表 97 — 可逆容器要求

rbegin()对应reverse_iterator(end())

因此在您的示例中,反向迭代器仍然对应于 end()。 `

关于c++ - 这是正确的行为吗? std::map 迭代器失效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33881285/

相关文章:

c++ - 在 C++ 中使用 'eigen' 库可以在大矩阵操作中击败 matlab 吗?

c++ - Busy-waiting和定时器中断在编程中的优缺点是什么?

Android C++ 构建错误 '__cxa_begin_catch'

c++ - it = map.find (element) == map.end() have it->second 是否正常?

Scala 并行无序迭代器

c++ - 返回 vector 元素 C++ 的地址

java - 为什么这个java迭代器循环也打印第一个元素?

c++ - 如何声明一个 std::map 以枚举为键,以不同签名为值的函数?

c++ - 使键等于(如果键存在于映射中)或严格小于映射中的给定输入

c++ - 按照键优先级的指定顺序按值对映射进行排序