简体   繁体   中英

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.

[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 . Even it!=enemy_vector.end() should be Undefined Behaviour.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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