Erasing an element from a vector using erase

别说谁变了你拦得住时间么 提交于 2020-01-25 13:06:06

问题


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;
}

回答1:


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.



来源:https://stackoverflow.com/questions/36679807/erasing-an-element-from-a-vector-using-erase

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!