为什么取消引用return()函数的迭代器后,我的程序崩溃? [英] Why my program crash after dereference of returned iterator of erase() function?

查看:70
本文介绍了为什么取消引用return()函数的迭代器后,我的程序崩溃?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是我的代码.我擦除了值为3的元素,并通过delete()函数获得了下一个迭代器.但是当我尝试打印它的价值时,它崩溃了,使我感到惊讶.有人知道这个问题吗?

Below is my code. I erase the element of which value is 3 and obtain next iterator by erase() function. But when I tried to print its value.It crashed to my surprise. Anyone know the problem??

int main()
{
    std::vector<int> a = {1, 2, 3, 4, 5}; 
    for(vector<int> ::iterator it=a.begin();it!=a.end();it++)
    {
        vector<int> ::iterator g;
        if(*it==3 )
        {
            g=a.erase(it);
        }
        cout<<*g<<endl;
    }

推荐答案

为什么我的程序在取消引用了delete()函数返回的迭代器后崩溃了?

Why my program crash after dereference of returned iterator of erase() function?

通过该迭代器进行间接并将其插入 cout 后,您可以继续递增(可能)无效的 it ,然后将其与另一个迭代器进行比较然后间接通过它.这会导致不确定的行为.

After you have indirected through that iterator and inserted it into cout, you proceed to increment it which is (potentially) invalid, and then also compare it to another iterator and later indirect through it. This results in undefined behaviour.

在此之前,如果 * it!= 3 ,您将通过未初始化的 g 进行间接操作,这将导致未定义的行为.

Even before that, in case *it != 3, you indirect through g which is uninitialised, which results in undefined behaviour.

这篇关于为什么取消引用return()函数的迭代器后,我的程序崩溃?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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