Program crashing at random points

I've been beating myself up over this, it's so frustrating.

I'm using SFML but it should matter, anyway.

What I'm trying to do is have a vector of enemies, and when the player kills one, a boolean is set to false, then, I use a pred function with a remove_if (in a while loop), and if that boolean is false, erase the element from the vector. Then, if enemies is empty, then create 5 enemies and push_back them into the vector.

I can't paste my entire code on here (500 lines so far), but here are the relevant parts. (So, still compilable if you put it in a standard program)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
  while (window.isOpen()) {
			if (spawned == false) {
				
				for (int i = 0; i < 5; i++) {
					Enemy enemyNew(enemy);
					enemyNew.setPosition(sf::Vector2f(100 + (i * 120), 100));
					enemies.push_back(enemyNew);
				};

				spawned = true;
			};

			if (enemies.empty()) {
				spawned = false;
			};

			for (int i = enemies.size() - 1; i >= 0; i--) {
					enemies.at(i).update(Time2, playerSprite, movement, current, enemies);
					enemies.at(i).moveToPlayer(playerSprite, 100, Time2);
					enemies.at(i).draw(window);
			};

			enemies.erase(std::remove_if(enemies.begin(), enemies.end(), predEnemy), enemies.end());
  }


It returns vector subscript out of range , but doesn't tell me where in my program?!?!

As soon as I kill the enemy, and the boolean is set to false, (which then the remove_if fires), it happens, but if I wait a little, say, 4 seconds, and then kill the enemy it works, but then crashes the next few times...

Any help is appreciated.
Last edited on
It returns vector subscript out of range

Since there's no use of the subscript operator in the code you posted, that problem is not here.
Use a debugger to check the call stack when your program crashes.
Topic archived. No new replies allowed.