Allowing my vector to iterate while both adding and removing values

Hi guys, I successfully implemented a system that allows bullets to destroy asteroids once they hit. The problem is that the next feature I need to add is that the asteroids break into smaller chunks (Just big ones). I added a function that adds 3 new rocks to the Vecter<Rocks> array when it hits the asteroid but it's giving me lots of trouble. I suspect that the problem is primarily that my iterator "bt" ("bt" is an iterator for asteroids) is breaking because it adds 3 new values to the vector which it can't handle somehow. That being said, I feel really stuck and unsure how to fix this. Any advice, suggestions, or clarity would be greatly appreciated.

A note: this program only breaks when I have only a few asteroids being used at a time


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
  // My function which handles colliding, sorry for the largeness.


void Asteroids::collisionHandling(){
	
	auto bt = rocks.begin();
	while (bt != rocks.end()) {
		bool BTwasDeleted = false;
		auto it = bullets.begin();
		while (it != bullets.end()){
			float minDistance = this->minDist((*bt)->getPoint(), it->getPoint(), (*bt)->getVector(), it->getVector());
			if (minDistance < (*bt)->getRadius()){
				BTwasDeleted = true;

				Point rockPoint = (*bt)->getPoint();
				Vector rockVector = (*bt)->getVector();

				
		

				bt = rocks.erase(bt);


				// calling this function will break my code
				this->breakBigRock(rockVector, rockPoint);


				it = bullets.erase(it);
				break;
			}
			else{
				++it;
			}
		}

		if (!BTwasDeleted){
			bt++;
		}
	}
}


// Code for breakBigRock (function which allows me to split a rock in 3)


// My constructor takes three parameters, the vector (velocity), the position (point), and the angular velocity (unimportant)

void Asteroids::breakBigRock(Vector rockVector, Point rockPoint){

mediumRock * firstRock = new mediumRock(Vector(rockVector.getDx(), rockVector.getDy() + 1.0f), 
														rockPoint, 2);
	rocks.push_back(firstRock);
	
	mediumRock * secondRock = new mediumRock(Vector(rockVector.getDx(), rockVector.getDy() - 1.0f),
														rockPoint, 2);
	rocks.push_back(secondRock);
	
	littleRock * thirdRock = new littleRock(Vector(rockVector.getDx() + 2.0f, rockVector.getDy()),
														rockPoint, 2);
	rocks.push_back(thirdRock);

}
Last edited on
The iterator bt becomes invalid if the push_back in breakBigRock(...) exceeds the capacy.

See:
http://www.cplusplus.com/reference/vector/vector/push_back/
Use an index in lieu of an iterator.
Topic archived. No new replies allowed.