矢量擦除循环给出错误,这是什么意思?

时间:2019-07-16 07:37:47

标签: c++ vector

在遍历向量以擦除元素时,出现错误。

    int i = 0;
    int j = 0;
    for (std::vector<bullet>::iterator it = 
 bullets.begin();it!=bullets.end();i++)
    {
        for (std::vector<bullet>::iterator it2 = 
 enemies.begin();it2!=enemies.end(); j++)
        {
            if (abs(bullets[i].pos.x - enemies[j].pos.x) < 5.f && abs(bullets[i].pos.y - enemies[j].pos.y)<5.f)
            {
                enemies.erase(enemies.begin() + j-1);
                enemies.shrink_to_fit();
                bullets.erase(bullets.begin()+i-1);
                bullets.shrink_to_fit();
            }
        };
    }

error message

1 个答案:

答案 0 :(得分:3)

您的代码没有多大意义,因为您正在弄乱其中的两种方法。

您可以使用索引:

for (int i = 0; i < myVec.size(); ++i)
{   
  if (IWantRemoved(myVec[i]))
  {
    myVec.erase(myVec.begin() + i);
  }
}

或迭代器:

for (auto it = myVec.begin(); it != myVec.end();)
{   
  if (IWantRemoved(*it))
  {
    it = myVec.erase(it);
    //this will recapture the iterator after erased element 
    //even if the vector was reallocated
  }
  else
  {
    ++it; //you cannot do this within for loop as you normally would because the iterator invalidation in case of element deletion.
  }
}

但是同时使用两者并没有多大意义。