简体   繁体   English

C ++,Visual Studio 2015,向量迭代器不可取消

[英]C++, Visual Studio 2015, Vector iterator not dereferencable

Ok, so i managed to write a method for deleting missles in my game, but i am constantly getting this error and i don't know why. 好的,所以我设法编写了一种删除游戏中的小漏斗的方法,但是我不断收到此错误,我也不知道为什么。 Any ideas how to deal with the problem? 任何想法如何处理该问题? Besides, i'd like to get rid of this i iterator, but then i don't know how to use properly delete and erase for the missle. 此外,我想摆脱这个迭代器,但是后来我不知道如何正确地删除和删除导弹。

    {
        int i = 0;
        for (auto it = missle_vector.begin(); it != missle_vector.end(); ++it) {
            score += missle_vector[i]->collision(i, missle_vector, enemy_vector, obstacle_vector, 1);
            displayMissle(**it);
            (*it)->moove(50, 0);
            i++;
        }
    } //this is how i use it

int Missle::collision(unsigned int i, vector <Missle*> &missle_vector, vector <Enemy*> &enemy_vector,
                            vector <Obstacle*> &obstacle_vector, bool G)
{
int hit=0;
for (auto it=enemy_vector.begin(); it!=enemy_vector.end(); )
{
    double x, y;
    x=(*it)->getX()-getX();
    y=(*it)->getY()-getY();
    if (x<64 && x>-151 && y<14 && y>-103)
    {
        delete  missle_vector[i];
        missle_vector.erase(missle_vector.begin() + i);
        delete *it;
        enemy_vector.erase(it);
        hit++;
    }
    else
        ++it;
}
if(G){
for (auto it=obstacle_vector.begin(); it!=obstacle_vector.end(); ++it)
    {
        double x, y;
        x=(*it)->getX()-getX();
        y=(*it)->getY()-getY();
        if (x<64 && x>-61 && y<14 && y>-61)
        {
            delete  missle_vector[i];
            missle_vector.erase(missle_vector.begin()+i);
        }
    }
}
if (getX()>1920)
{
    delete missle_vector[i];
    missle_vector.erase(missle_vector.begin()+i);
}
return hit;
} //method itself

This is an assertion: 这是一个断言:

Vector iterator not dereferencable

and it means you are derefencing and iterator which for example is end iterator. 这意味着您正在取消引用和迭代器,例如结束迭代器。 For example this short example will generate this assertion: 例如,以下简短示例将生成以下断言:

std::vector<int> v;
*v.end();

this assertion should appear at runtime during debugging and will allow you to find exact place where problem exissts. 此断言应在调试期间的运行时出现,并允许您找到存在问题的确切位置。 In Visual Studio you can use debugger to lookup local variables, call stack. 在Visual Studio中,您可以使用调试器查找局部变量,调用堆栈。

[edit] [编辑]

one place where you can get this assertion in your code is here: 您可以在代码中获得此断言的一个地方是:

 enemy_vector.erase(it);

this should be: 这应该是:

 it = enemy_vector.erase(it);

otherwise in next iteration your it will be invalid and *it will result in Vector iterator not dereferencable . 否则,在下一次迭代中,它将无效,并且*将导致Vector iterator not dereferencable Even it!=enemy_vector.end() should be Undefined Behaviour. 即使是it!=enemy_vector.end()应该是未定义的行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM