矢量迭代器不能解除引用? [英] Vector iterator not dereferencable?

查看:292
本文介绍了矢量迭代器不能解除引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这段代码中收到了这个错误:

I'm getting that error with this code:

for(std::vector<AguiTimedEvent*>::iterator it = timedEvents.begin();
    it != timedEvents.end();)
{
    if((*it)->expired())
    {
        (*it)->timedEventCallback();
        delete (*it);

        it = timedEvents.erase(it);
    }
    else
        it++;
}

可能是什么问题?

定时事件有时会在调用其回调时推送新的事件,可能会这样做

the timed event sometimes pushes a new one in when its callback is called, that might do it

谢谢

推荐答案

如果循环遍历向量并且回调函数导致向量被添加到,则向量中的所有迭代器都可能无效,包括循环变量 it

If you are looping through a vector and the callback function causes the vector to be added to, then all iterators into the vector may be invalidated including the loop variable it.

在这种情况下(回调修改向量)你可能最好使用索引作为循环变量。

In this case (where the callback modifies the vector) you are probably better off using an index as your loop variable.

您可能需要对设计进行一些全面的分析,以确保您不会创建任何意外的无限循环。

You probably need to do some thorough analysis of the design to make sure that you aren't going to create any unexpected infinite loops.

例如

for(std::vector<AguiTimedEvent*>::size_type n = 0;
    n < timedEvents.size();)
{
    if(timedEvents[n]->expired())
    {
        timedEvents[n]->timedEventCallback();
        delete timedEvents[n];

        timedEvents.erase(timedEvents.begin() + n);
    }
    else
        n++;
}

这篇关于矢量迭代器不能解除引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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