Erasing an element from a vector using erase

2019-09-05 23:04发布

So I wanted to do thing like mentioned above. And I came up with a brilliant idea when it comes to a usual iteration, third part of the method. But I don't know how to deal with the problem when I have a loop inside a loop. And yes, I know it's caused by skipping elements while erasing.

int Collision::missleCollision(vector <Missle*> &missle_vector, vector <Enemy*> &enemy_vector,
                               vector <Obstacle*> &obstacle_vector, bool G)
{
    int hit=0;
    for (auto it=missle_vector.begin(); it!=missle_vector.end(); ++it)
    {
        for (auto jt=enemy_vector.begin(); jt!=enemy_vector.end(); ++jt)
        {
            double x, y;
            x=(*jt)->getX()-(*it)->getX();
            y=(*jt)->getY()-(*it)->getY();
            if (x<64 && x>-151 && y<14 && y>-103)
            {
                delete *it;
                it=missle_vector.erase(it);
                delete *jt;
                jt=enemy_vector.erase(jt);
                hit++;
            }
        }
    }

    if(G){
        for (auto it = missle_vector.begin(); it!=missle_vector.end(); ++it)
        {
            for (auto jt = obstacle_vector.begin(); jt!=obstacle_vector.end(); ++jt)
            {
                double x, y;
                x=(*jt)->getX()-(*it)->getX();
                y=(*jt)->getY()-(*it)->getY();
                if (x<64 && x>-61 && y<14 && y>-61)
                {
                    delete  *it;
                    it = missle_vector.erase(it);
                }
            }
        }
    }

    for (auto it = missle_vector.begin(); it != missle_vector.end(); )
    {
        if ((*it)->getX() > 1920)
        {
            delete *it;
            it = missle_vector.erase(it);
        }
        else
        it++;
    }
    return hit;
}

标签: c++ vector erase
1条回答
Bombasti
2楼-- · 2019-09-05 23:35

The general pattern for erasing something from a range while traversing the same range (and not using something high-level like std::remove_if) is like this:

for (auto it = v.begin(); it != v.end(); )
{
    if (pred(it)) { it = v.erase(it); }
    else          { ++it;             }
}

Note that you don't increment the iterator in the for header.

查看更多
登录 后发表回答