-1

I just recently started experimenting with vectors and I keep running into this problem when erasing a spot in the vector. Once it executes the erase() function it causes the application to crash and a memory access violation occurs.

Here is the code for the function:

 bool moveBullets(void)
 {
   int i = 0;
   for(std::vector<sf::Sprite>::iterator it = laserList.begin(); it != laserList.end(); it++)
   {
    laserList[i].move(0.0f, -2.0f);
    int id = 0;
        for(std::vector<sf::Sprite>::iterator s = enemy.begin(); s != enemy.end(); s++)
        {
            if(checkCollision(laserList[i], enemy[id]))
            {
                laserList.erase(laserList.begin() + i);

                //enemy.erase(s);
                std::cout << "COLLISION";
            } 
            id++;
        }
    i++;
}
return 0;

}

Basically what this function does it run through a vector and checks another vector for a collision. So vector A will check for a collision all the way through vector B. Once it has fully checked vector B it will go to the next position in vector A and repeat.

However it works fine until it runs the erase() function. Then it causes a memory access error.

Thanks for the help! :-)

Bryce910
  • 23
  • 4
  • 5
    [Duplicate 1](http://stackoverflow.com/questions/8597240/how-to-delete-an-element-from-a-vector-while-looping-over-it). [Duplicate 2](http://stackoverflow.com/questions/9927163/erase-element-in-vector-while-iterating-the-same-vector). [Duplicate 3](http://stackoverflow.com/questions/3938838/erasing-from-a-stdvector-while-doing-a-for-each). [Duplicate 4](http://stackoverflow.com/questions/4713131/removing-item-from-vector-while-iterating). – Cornstalks Dec 18 '14 at 05:30

1 Answers1

1

When you call erase, you modify laserList. That makes it invalid, because it pointed into the previous value of laserList. But then you increment it. You can't increment an iterator to contents that no longer exist. That makes no sense.

David Schwartz
  • 179,497
  • 17
  • 214
  • 278
  • So I would need to skip the increment if I erase()? – Bryce910 Dec 18 '14 at 05:41
  • @Bryce910 That's the first step. The next step is figuring out what you do want to do if you `erase`. It's certainly not increment `it`, but what is it? Your code does not include any sane way to continue after modifying the vector. You need to decide what you want to do and write the code to do it. Do you want to start over at the beginning of the modified vector? Do you want to use some logic to find a particular resume point in the new vector? Decide what you want to do and write the code to do it. – David Schwartz Dec 18 '14 at 05:54