gpt4 book ai didi

c++ - map C++ 中的迭代器失效

转载 作者:太空狗 更新时间:2023-10-29 20:01:54 26 4
gpt4 key购买 nike

我有一个示例程序,我试图在其中查看迭代器在从 map 中删除元素时如何失效。

程序在这里:

#include <iostream>
#include <map>

using namespace std;

int main(int argc, char *argv[])
{

map<int, int> myMap;

myMap.insert(pair<int, int>(0, 2));
myMap.insert(pair<int, int>(1, 4));
myMap.insert(pair<int, int>(3, 18));
myMap.insert(pair<int, int>(2, 20));

map<int, int>::iterator it;

for(it = myMap.begin(); it != myMap.end(); ++it)
{
myMap.erase(it); // erasing the element pointed at by iterator

cout << it->first << endl; // iterator is invalid here
}
return 0;
}

问题是我得到的输出是:

0
1
2
3

为什么迭代器没有失效并给我错误的结果。任何帮助将不胜感激。

Documentation of C++ STL maps says that: References and iterators to the erased elements are invalidated. Other references and iterators are not affected.

最佳答案

使用无效的迭代器是未定义的行为。在这种情况下,任何事情都有可能发生。

您为什么会看到这些值?迭代器包含指向某 block 内存的指针,纯属偶然,该内存尚未归还给系统并且尚未被覆盖。这就是为什么您仍然可以看到已经“死”的值。

它不会改变任何东西,它仍然是未定义的行为,下次你运行程序时, map 元素所在的内存页可能已经再次返回给操作系统,你会遇到访问冲突(段错误) ...

关于c++ - map C++ 中的迭代器失效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49895485/

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