std::vector erase problem

Started by
2 comments, last by rip-off 16 years, 2 months ago
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->GetIsPlaying() == false) { delete m_GargabeCollection; m_GargabeCollection.erase(q); } } if i have 2 elements in the vector and if the first gets deleted with:: delete m_GargabeCollection; 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
Advertisement
  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.
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 ;)
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.

This topic is closed to new replies.

Advertisement