I'm a beginner c++ programmer and I tried to make a game, but there's one error that keeps popping up.
Debug Assertion Failed! <...> line 256.
I think that the problem is in this part of the code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
void Level::update()
{
// here is where we'll be able to deal with fireball moving
// and extra stuff
for (Iter = npc.begin(); Iter != npc.end(); Iter++)
{
(*Iter)->idleUpdate();
if ((*Iter)->isAlive() == false)
{
Sprite *temp = *Iter;
Iter--;
delete temp;
npc.remove(temp);
}
}
}
Could you check for anything I might have done wrong here?
Thanks in advance :)
void Level::update()
{
bool t = false;
// here is we'll be able to deal with fireball moving
// and extra stuff
for (Iter = npc.begin(); Iter != npc.end(); Iter++)
{
(*Iter)->idleUpdate();
if (t)
Iter--;
t = false;
if ((*Iter)->isAlive() == false)
{
Sprite *temp = *Iter;
if (Iter != npc.begin())
{
Iter--;
t = true;
}
delete temp;
npc.remove(temp);
}
}
}
That took care of the error, but the game itself just crashes. If there are no other mistakes here, I guess there must be a mistake somewhere else. Thanks anyway :)
The problem is at the beginning. If it is at the beginning you remove the 'Sprite' and thus invalidate 'Iter'.
Better would be something like that:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
void Level::update()
{
// here is we'll be able to deal with fireball moving
// and extra stuff
Iter = npc.begin();
while(Iter != npc.end())
{
(*Iter)->idleUpdate();
if ((*Iter)->isAlive())
++Iter;
else
{
Sprite *temp = *Iter;
Iter = npc.erase(Iter);
delete temp; // Delete the object after you erased it from the container otherwise you'd have an invalid object in you containe for a short while
}
}
}
The STL containers erase/remove methods remove elements. But if you use the STL algorithm remove, remove_if, I don't think they do removal.What the function return is a "marker" where everything before "marker" is retain and all else after are elements to be removed but they are not removed yet. You need one more step to call STL containers erase/remove methods to do actual removal.
erase() removes the object pointed to by the iterator and returns the next valid iterator.
remove() removes all objects which equals to the object provided. It does not return anything