deleting elements in a vector

Hello,

I'm doing a remake of Yoshi's Island and I'm using a vector to keep track of instances. However, I'm having trouble removing particular elements from the vector.

This is my best shot so far:

for(vector<ShyGuy*>::iterator it = m_shyguylist->begin(); it != m_shyguylist->end(); ++it)
{
if(*it == shyguyptr)
{
m_shyguylist->erase(it);
}

}

The program crashes on an assertion failure after the first instance gets deleted. I know this is not the way to do it, so:

Can anyone show me a viable way to remove elements from a vector?

Much thanks in advance!

I see nothing wrong with what you're doing, except that the objects were probably dynamically allocated and you did not delete
when you erase from a vector, the iterators are invalidated so you can't continue with the loop that way.
Try with it=m_shyguylist->erase(it)-1;
Last edited on
oh yes, I feel silly now for saying it was fine. erase should return the new end, so then it will then it will only continue to check the last element. If you don't actually need to use delete, you could use remove from <algorithm>
1
2
3
4
{
    vector<ShyGuy*>::iterator temp = remove(m_shyguylist->begin(), m_shyguylist->end(), shyguyptr);
    m_shyguylist->erase(temp, m_shyguylist->end());
}
Topic archived. No new replies allowed.