Original Post
Hi, I'm having some difficulty with vectors in C++, and I was hoping someone could provide me with some insights. Right now I'm pretty sure that the code I have dealing with vectors is having border cases that cause the problems (like when the iterator is on the last element of the vector), but I'm not 100% sure that's the case. Here's the code that's causing me problems: Originally after the line "siSprite=m_vSprites.erase(siSprite);" i had "siSprite--;" which seemed to make it crash less, but still crashes. Another one of my problems is that I don't think I fully know how vectors work, like when I'm doing an erase, does it still leave a NULL element in the vector, or does it "shift" all the elements that are deleted over by one? If it's just leaving it NULL then the problem could be I'm trying to do sprite actions on null elements. Another thing I don't understand is what's going to happen when the loop has to erase the last element of the vector, what is the iterator returned from the "erase" function going to be? Is it undefined?
void GameEngine::UpdateSprites()
{
// Expand the capacity of the sprite vector, if necessary
if (m_vSprites.size() >= (m_vSprites.capacity() / 2))
m_vSprites.reserve(m_vSprites.capacity() * 2);
// Update the sprites in the sprite vector
RECTFLOAT rcOldSpritePos;
SPRITEACTION saSpriteAction;
vector<Sprite*>::iterator siSprite;
for (siSprite = m_vSprites.begin(); siSprite != m_vSprites.end(); siSprite++)
{
// Save the old sprite position in case we need to restore it
rcOldSpritePos = (*siSprite)->GetPosition();
// Update the sprite
saSpriteAction = (*siSprite)->Update();
// Handle the SA_ADDSPRITE sprite action
if (saSpriteAction & SA_ADDSPRITE)
// Allow the sprite to add its sprite
AddSprite((*siSprite)->AddSprite());
// Handle the SA_KILL sprite action
if (saSpriteAction & SA_KILL)
{
// Notify the game that the sprite is dying
SpriteDying(*siSprite);
// Kill the sprite
delete (*siSprite);
siSprite=m_vSprites.erase(siSprite);
continue;
}
// See if the sprite collided with any others
if (CheckSpriteCollision(*siSprite))
// Restore the old sprite position
(*siSprite)->SetPosition(rcOldSpritePos);
}
}