Vector size is completely wrong...

I'm writing a snake game using sfml. I'm storing the body in a vector, and I change each of the vectors in a loop that looks like so:
1
2
3
4
5
6
7
8
9
void Snake::MoveBody() {
	//this->GhostTail = this->Body[this->Body.size() - 1];
	int j = this->Body.size(); //Unused, just for debugging
	this->GhostTail = this->Body.back();
	for (int i = this->Body.size() - 1; i > 1; i--) {
		this->Body[i] = this->Body[i - 1];
	}
	this->Body[0] = this->Head;
}


The problem I'm facing is that in this loop, j gets assigned the value of 3 (That's right) and i gets assigned the value of -858993460 (That's wrong!)
Where am I going wrong? I'm sorry if it's a very trivial mistake, I'm very much a beginner.
Last edited on
The first thing I see wrong is that the loop will only run if Body.size() - 1 is less than 1, and if it does run you will be accessing the array out of bounds.

Oops let me modify that! Thanks
Also, I don't think you need to use this-> everywhere.
-858993460 corresponds to the bit pattern held by the value 0xCCCCCCCC, which is the value uninitialized variables are given in VC++ debug builds. I think you're looking at the value of i in the debugger before it officially exists.
Yeah, I figured, so I changed the loop and it would run through the loop. I fixed the problem and here is a working version of loop:

1
2
3
for (int i = this->Body.size() - 1; i != 0; i--) {
	this->Body[i] = this->Body[i - 1];
}
@TheIdeasMan, What could one do differently instead of this->?
@Optimistic Peach

Member functions have direct access to member variables, so refer to them directly:

Body.size() not this->Body.size()

instead of calling the size function each time, call it once before the loop and assign to a variable, then use it in the loop.

The STL size functions return a value of type std::size_t, so you should use this to avoid an implicit cast to int, and a possible warning from the compiler.

1
2
3
4
std::size_t BodySize =  Body.size() -1;
for (std::size_t i = BodySize ; i > 1;  i--) { // i must stop at 1, because of the next line
    Body[i] = Body[i - 1];
}
@TheIdeasMan Ok, cool, that will make my code look alot nicer! Thanks!
Topic archived. No new replies allowed.