c++ vector objects erase function


Im a CS student new to C++ as i used to use java, and well decided to google around to find something to remove an object from my vector (aka arraylist in java) at any given index.

i found it at here at (http://www.cplusplus.com/reference/stl/vector/) which basically gave me the answer. So i implemented it in mine and this is how i wrote it...

N.B. this is for a project regarding the board game "Talisman" . Now each "Character" object has a vector of type "Objects".. this vector is basically their "belt" which is where they store their swords, armour, and magical object.

anyways here is my portion of the code:

void Character::takeObjectFrom(Character y, int i)
y.objects.erase(y.objects.begin() + i);

and it is being called in the driver/(main) as follows...

c[0].takeObjectFrom(c[1], 1);

now for some reason, it does not remove the object from the character y array... is there a reason why? everything is exactly the same as i've seen on forums and they claim that it is working... everything works fine with push and pop, but that just acts like a stack, which is not what i want for here..

any ideas why this is not working?

note: the c[0] does get the object at c[1]'s index, BUT c[1] still holds that object when it should have been erased...

Any help would be appreciated thanks!
Last edited on
You may just be accessing an invalidated index in the vector. Check the size of c[1]'s objects member after you call erase. The size will let you know whether it works or not.

1. Use a debugger. Can't stress this more than enough to all the beginners out there. Will save hours.

2. Try using assertions. Your problem is a good example that shows benefits of assert statements.
void Character::takeObjectFrom(Character y, int i) pass a copy of the object
void Character::takeObjectFrom(Character &y, int i) pass the object (pass by reference)

You accidentally create a dozen clones of yourself and shoot them all in the foot. Providing emergency medical assistance is impossible since you can’t tell which are bitwise copies and which are just pointing at others and saying, "That’s me, over there."
wow that was soooo noob on my part... lmao

thanks a ton ne555, that solved my issue! :)

A++ .... correction .. C++ lol
Last edited on
Topic archived. No new replies allowed.