Reputation: 39
My program creates projectiles that move forward, if they go out of certain bounds, they are to be deleted from the vector that they are stored in. The vector stores xcord, ycord, zcord, and their respective directions.
int size = bullet.size();
for(int i = 0; i < size; i+=6)
{
float xc = bullet[i];
float yc = bullet[i+1];
float zc = bullet[i+2];
float xd = bullet[i+3];
float yd = bullet[i+4];
float zd = bullet[i+5];
if(xc > 100 || yc > 10 || zc > 100 || xc < -100 || yc < -10 || zc < -100)
{
bullet.erase(bullet.begin()+i, bullet.begin()+i+5);
size=size-6;
i = i-6;
}
else
{
glEnable(GL_TEXTURE_2D);
glBindTexture ( GL_TEXTURE_2D, texture_id[3] );
glPushMatrix();
glTranslatef( xc+(xd/2), yc+(yd/2), zc+(zd/2)); //x y z coord of sphere
glRotatef( 0,0,1,0);
glRotatef( -80,1,0,0);
glRotatef( 0,0,0,1);
glScalef( 0.10f, 0.10f, 0.10f);
gluQuadricTexture(quadric,1);
gluSphere(quadric,10.0,72,72);
glPopMatrix();
glDisable(GL_TEXTURE_2D);
bullet[i] = xc+xd;
bullet[i+1] = yc+yd;
bullet[i+2] = zc+zd;
}
}
But when a "bullet" goes out of bounds my program seems to crash. Any ideas?
Well changing
bullet.erase(bullet.begin()+i, bullet.begin()+i+5);
to
bullet.erase(bullet.begin()+i, bullet.begin()+i+6);
seems to have fixed it
For those interested
bullet.push_back(xpos);
bullet.push_back(0.0f);
bullet.push_back(zpos);
bullet.push_back(nxpos);
bullet.push_back(nypos);
bullet.push_back(nzpos);
happens whenever the mouse is clicked
Upvotes: 0
Views: 1888
Reputation: 1823
http://www.cplusplus.com/reference/vector/vector/erase/
Iterators specifying a range within the vector] to be removed: [first,last). i.e., the range includes all the elements between first and last, including the element pointed by first but not the one pointed by last.
The problem is that you're deleting only 5 elements instead of 6.
Upvotes: 3
Reputation: 258618
You have
i < size
as your condition, and accessing elements
bullet[i] .... bullet[i+5]
See anything wrong there? What happens when i
reaches size-1
. You'll access bullet[size + 4]
, right?
Upvotes: 5