0

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.

user1198065
  • 210
  • 3
  • 10

2 Answers2

6
 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
Nawaz
  • 353,942
  • 115
  • 666
  • 851
  • it works, but can you explain me the problem in more detail. what is the difference between remove and erase. – user1198065 Nov 15 '12 at 20:12
  • @user1198065: There are lots of topics on this site. You can search them. For example, see this : http://stackoverflow.com/questions/596162/can-you-remove-elements-from-a-stdlist-while-iterating-through-it – Nawaz Nov 15 '12 at 20:13
1

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

Community
  • 1
  • 1
Thomas
  • 174,939
  • 50
  • 355
  • 478