问题描述:

Hi in my project that's roguelike RPG im using vector to keep polymorphic indicators to all monsters, parts of abstract class Mob. The problem is during fight - there's a function that return iterator selecting nob that we are attacking(i skipped for tests that in case here's no monster it returns begin of vector).

 vector<Mob*>::iterator Hero::TryAttack(vector <Mob*> monsters)

{

int trying_x = pos_x, trying_y = pos_y;

switch (DIR)

{

case UP: trying_y--;

case DOWN: trying_y++;

case LEFT: trying_x--;

case RIGHT: trying_x++;

}

if (!monsters.empty())

{

for (vector <Mob*>::iterator i = monsters.begin(); i != monsters.end(); i++)

{

if ((*i)->pos_x == trying_x && (*i)->pos_y == trying_y)

{

return i;

}

}

}

return monsters.begin();

}

and when i calling that function here:

switch (hero.CheckAction())

{

case ATTACK:

{

//delete rat3;

if(!monsters.empty())

monsters.erase(hero.TryAttack(monsters));

test_map.Draw(monsters, NPCs);

break;

}

default: break;

}

there's poping assertion failure:

img

i understand that erase returns next element after deleted but how can i delete that only one existing element in vector?

网友答案:
Hero::TryAttack(vector <Mob*> monsters)

You are passing monsters by value. Returned iterator refers to nonexistent copy of the vector. Pass it by reference:

Hero::TryAttack(vector <Mob*>& monsters)
相关阅读:
Top