void testApp::mousePressed(int x, int y, int button){
//this loop splits the ball in 4 parts
//and erases a ball every time you click on one
for(int i = 0; i < balls.size(); i++){
if((x > balls[i].pos.x && x < balls[i].pos.x + tmpBall.radius)&&
(y > balls[i].pos.y && y < balls[i].pos.y + tmpBall.radius))
balls.pop_back();
elseif((x > balls[i].pos.x && x < balls[i].pos.x + tmpBall.radius)&&
(y < balls[i].pos.y && y > balls[i].pos.y - tmpBall.radius))
balls.pop_back();
elseif((x < balls[i].pos.x && x > balls[i].pos.x - tmpBall.radius) &&
(y > balls[i].pos.y && y < balls[i].pos.y + tmpBall.radius ))
balls.pop_back();
elseif((x < balls[i].pos.x && x > balls[i].pos.x - tmpBall.radius) &&
(y < balls[i].pos.y && y > balls[i].pos.y - tmpBall.radius ))
balls.pop_back();
}
}
The only proble is that with the pop_back() function you remove the
last element from the vector
and what I want to do is remove the specific element I press on
which in this case is ball[i]
anybody has an idea how to do that?
Thanks in advance
Note that if insertion and removal of elements in the middle of the container is necessary, you might want to look into a different container. A deque or list might be applicable.
Removing elements from the middle of a vector is very expensive because the vector stores the elements in a contiguous block of memory; when an element is removed, the remaining elements must be moved to retain that guarantee (which explains why the iterators become invalid).