So I am getting a runtime error and I have narrowed down the problem to this method.

I am still learning about iterators and I assume that the problem is with this part of the code, getting the expression error

list iterator not decrementable.

Any help would be appreciated.

void Level::update()
{
	
	for (Iter = npc.begin(); Iter != npc.end(); Iter++)
	{
			//dereferance *Iter to use pointer notation
			(*Iter)->idleUpdate();

			if ((*Iter)->isAlive() == false)
			{
				sprite *temp = *Iter;

				Iter--;
				delete temp;
				npc.remove(temp);				
		}
	}
}

Recommended Answers

All 5 Replies

Why are you using delete on something that wasn't new'ed?
Why would you even attempt to do something with temp after calling delete on it (if it were something you could delete)?

maybe you want npc.erase(iter); When you do that I have found that you need to start the loop all over again because the value of iter is invalidated.

Well if I remember correctly when delete is called on a pointer to an object the deconstructor is called for that object?

I figured the pointer was still there tho referencing that object so calling the remove on a list with a referance to that object then it would get removed off the stack?

Well if I remember correctly when delete is called on a pointer to an object the deconstructor is called for that object?

Automatic objects go out of scope and do the same thing. But no, it's not simply that delete is used on a pointer. If you use a pointer is used to new something, and you delete only what you have new'ed. The key is that new/delete are a pair -- you don't use one without the other.

Here is my code for adding an enemy to the board.

void Level::addEnemies(int num)
{
	int i = num;

	while (i > 0)
	{
		int xpos = int(float(((rand() % width) + 1) - 1));
		int ypos = int(float(((rand() % height) + 1) - 1));
		
		if (level[xpos][ypos] != TILE_WALL)
		{
			Enemy *temp = new Enemy(this, drawArea, SPRITE_ENEMY, (float)xpos, (float)ypos);

			temp->addGoal(player);

			addNPC((sprite *)temp);

			i--;
		}
	}
}
void Level::addNPC(sprite *spr)
{
	npc.push_back(spr);
}

this is getting pushed on the stack which I iterate through.

So the problem is the code works well until I remove, possably the last on the stack? I am guessing that decrement of the last/first on the stack it throws up.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.