简体   繁体   中英

Having an issue with c++ stl lists

I have the following function.

void BulletFactory::update(Uint32 ticks) {
  std::list<Sprite*>::iterator it = activeBullets.begin();
  while (it != activeBullets.end()) {
    (*it)->update(ticks);
    if(!((*it)->inView())) {
      activeBullets.remove(*it);
      Sprite* temp = *it;
      it++;
      inactiveBullets.push_back(temp);
    } else {
      it++;
    }
  }
}

when the condition !((*it)->inView()) is being true there is a segmentation fault. I am not able to see the problem.

edit: forgot to mention that activeBullets and inactiveBullets are two lists.

 activeBullets.remove(*it);
 Sprite* temp = *it; //<--- problem
 it++; //<-- problem

should be:

  Sprite* temp = *it;
  it = activeBullets.erase(it); //use erase
  //it++; don't increment it

You must not modify the element that the iterator is pointing to, because it invalidates the iterator. See this question for solutions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM