Subscript out of Range Vector C++

Started by
4 comments, last by Alberth 4 years, 3 months ago

Hello,

I am trying to add my bullet struct into a vector of bullets. So I can shoot multiple bullets. However I get a subscript out of range when I try to run the program. I can't figure out why its not adding the bullets to the vector.

BULLET Bullet;

vector <BULLET> Bullets;

	if (IsKeyPressed(KEY_SPACE)) //add bullets to the vector
		{
			Bullet.Visible = true;
			Bullets.push_back(Bullet);
		}

		if (Bullet.Visible) //shooting the bullet(s)
		{
			for (int i = 0; i <= Bullets.size(); i++)
			{
				DrawCircleV(Bullets[i].Pos, Bullets[i].Rad, RED);
			}
		}
Advertisement

Your for loop has a range error.

for (int i = 0; i <= Bullets.size(); i++)

Should be this:

for (int i = 0; i < Bullets.size(); i++)

You are running off the vector by 1; size = last index + 1 ( 1 based size vs 0 based index )

h8CplusplusGuru said:

Your for loop has a range error.

for (int i = 0; i <= Bullets.size(); i++)

Should be this:

for (int i = 0; i < Bullets.size(); i++)

You are running off the vector by 1; size = last index + 1 ( 1 based size vs 0 based index )

Thank you, it works now. A simple oversight on my part.

You're better off not indexing here anyway.

for (auto const& bullet: Bullets) {
	DrawCircleV(bullet.Pos, bullet.Rad, RED)
}

Stephen M. Webb
Professional Free Software Developer

LeftyGuitar said:
A simple oversight on my part.

I was also always confused and messing about with the off-by-one problems with indices.

At some point I had enough of it and decided to always use 0-based indices from that moment. That made life a lot simpler, as ‘suddenly’, relations between size, index, max-index, and number of items became fixed, thus ending the confusion.

This topic is closed to new replies.

Advertisement