map C++中的迭代器失效 [英] iterator invalidation in map C++

查看:62
本文介绍了map C++中的迭代器失效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a sample program in which I am trying to see how the iterator invalidates while deleting the elements from a 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;
}

问题是我得到的输出是:

The problem is that I am getting output is:

0
1
2
3  

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

Why the iterator is not invalidating and giving me wrong results. Any help would be highly appreciated.

C++ STL 映射文档说:引用和迭代器到被擦除的元素无效.其他引用和迭代器不受影响.

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

推荐答案

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

Using an invalidated iterator is undefined behaviour. In such case, anything could happen.

你为什么会看到这些值?迭代器包含一个指向某块内存的指针,纯属偶然,这块内存还没有返回给系统,也没有被覆盖.这就是为什么您仍然可以看到已经死"的值.

Why do you see the values? The iterator contains a pointer to some piece of memory, by pure accident, this memory has not yet been returned to the system and has not yet been overwritten. This is why you still can see the already "dead" values.

它没有改变任何东西,它仍然是未定义的行为,下次运行程序时,映射元素所在的内存页面可能已经再次返回给操作系统,并且您会收到访问冲突(分段错误)...

It does not change anything, it remains undefined behaviour, and the next time you run the program, the memory page the map element resided in could already have been returned to the OS again and you get an access violation (segmentation fault)...

这篇关于map C++中的迭代器失效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆