Vector - Erase object from vector


#1

How does one erase a Game Object from the vector . Anyone spot what Im doing wrong

	//----------------------------------------------------------------
	//PROJECTILES COLLISION TESTING
	if (!projectiles.empty())
	{
		for (auto vehicle : this->vehicles)
		{
			for (auto projectile : this->projectiles)
			{

				if (projectile->getSprite() != NULL)
				{
					cocos2d::Rect rect1 = vehicle->getSprite()->getBoundingBox();
					cocos2d::Rect rect2 = projectile->getSprite()->getBoundingBox();

					if (rect1.intersectsRect(rect2))
					{
						vehicle->setDamage(projectile->returnType());
						cocos2d::Vec2 location = projectile->getSprite()->getPosition();
						this->removeChild(projectile->getSprite());
						projectiles.erase(projectile);//This DOT is highlighted red and wont work
						projectile->DisposeObject();
						Explosion* explosion = new Explosion();
						explosion->getSprite()->setPosition(location);
						this->addChild(explosion->getSprite());
					}
				}
			}
		}

	}

Objects Inherit like this and my vector is

GameObject -> GameObjectPhysics - > Bullet

std::vector<GameObject*> projectiles;

Thanks Very Much any help


#2

I use std::remove`

#include <algorithm>
...
vec.erase(std::remove(vec.begin(), vec.end(), 8), vec.end());

#4

Not sure what this does, also doesn’t work.

Is there a way at just deleting the current iter (projectile)?


#5

Maybe use Vector instead and then you can give an index or pointer.
If you’d stick with vector, I think it should be like this:

int index = 5;
vec.erase(vec.begin() + index);

#6

How do I know which index the object is on ? Some kind of increment int during looping the vector ?


#7

Ah, so you don’t know the index. Then eraseObject from Vector class is the easiest option.
In vector you can find the iterator:

auto it = find(vec.begin(), vec.end(), itemToFind);
if (it != vec.end()){
    vec.erase(it);
}