SFML community forums
Help => General => Topic started by: Baduo127 on June 18, 2016, 09:36:02 pm
-
I'm trying to create a vector which contains several rectangles (blockRect) in the block class, when the third rectangle (blockRect) in the vector array hit another rectangle (endRect) defined in another class, it (the third blockRect in the vector) should be deleted in the vector, but it gives me a error: vector subscript out of range, I can't figure out why, any help please?
this is the code which I try to delete the third blockRect in the vector (there is 4 blockRect in Vec1, and Vec 2 basicly contains endRect for collision):
for (int i = 0; i < Vec2.size(); i++) {
if (Vec2.endRect.getGlobalBounds().intersects(blocksClass.Vec1[2].blockRect.getGlobalBounds())) {
blocksClass.Vec1.erase(blocksClass.Vec1.begin() + 2);
}
}
-
You shouldn't work with magic numbers such as 2, especially if you're iterating over a vector and at the same time remove elements. Whenever you access a random element in a vector you should make sure that it actually exists, by checking against the vector's size.
-
I'm curious as to your creation of the vector (Vec1). You say that they are a vector of blockRect but it looks like blockRect is a member of whatever the vector is actually holding.
Similar to Exploiter's comment, any reason you're blindly removing a specific element regardless of how many times you do this loop?
-
i think there is mistake in your code snippet, Vec2.endRect should be some thing like this vec2[i].endRect.