Sign in to follow this  
of_ownage

std::vector erase problem

Recommended Posts

hi, i have a problem with my std::vector<>. std::vector<CSound*>::iterator q = m_GargabeCollection.begin(); for(UINT i = 0; i < m_GargabeCollection.size(); ++i, ++q) { if(m_GargabeCollection[i]->GetIsPlaying() == false) { delete m_GargabeCollection[i]; m_GargabeCollection.erase(q); } } if i have 2 elements in the vector and if the first gets deleted with:: delete m_GargabeCollection[i]; and then erased from the array with m_GargabeCollection.erase(q); and the loop ends and the iterator gets incremented ++q then the program crashes because the iterator is not valid anymore, how can i fix that? thank you

Share this post


Link to post
Share on other sites
  1. As your first option, boost::ptr_vector.
  2. As a slightly more complex alternative, boost::shared_ptr and std::remove_if:
    bool dead(const boost::shared_ptr<Sound> &s)
    { return ! s->isPlaying(); }

    std::vector< boost::shared_ptr<Sound> > vect;

    vect.erase(std::remove_if(vect.begin(),
    vect.end(),
    dead),
    vect.end());

  3. You can approximate the above with naked pointers (though that would be a waste of time) using std::for_each to delete them beforehand).
  4. If you really insist on doing things the hard way, use the return value of erase, but that is just needlessly complicated.

Share this post


Link to post
Share on other sites
or i think a bit^^

std::vector<CSound*>::iterator q = m_GargabeCollection.begin();
for(; q != m_GargabeCollection.end();)
{

if( (*q)->GetIsPlaying() == false)
{
delete (*q);
q = m_GargabeCollection.erase(q);
}
else
{
++q;
}
}

forgot that erase returns a new iterator ;)

Share this post


Link to post
Share on other sites
I have to strongly agree with ToohrVyk, you are choosing the worst option here. If you persist in trying to manually manage your memory, you will end up with errors. Are the pointers shared? . If so, then boost::shared_ptr is usually the best tool for the job. If not, then boost::ptr_vector will probably be best.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this