使用擦除从向量中擦除元素 [英] Erasing an element from a vector using erase
本文介绍了使用擦除从向量中擦除元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
所以我想做上面提到的事情.当涉及到通常的迭代,方法的第三部分时,我想出了一个绝妙的主意.但是当我在一个循环中有一个循环时,我不知道如何处理这个问题.是的,我知道这是由擦除时跳过元素引起的.
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;
}
推荐答案
在遍历同一范围的同时从范围中擦除某些内容的一般模式(而不是使用诸如 std::remove_if
) 是这样的:
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; }
}
请注意,您不要增加 for
标头中的迭代器.
Note that you don't increment the iterator in the for
header.
这篇关于使用擦除从向量中擦除元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文