delete from a vector

Mar 27, 2009 at 6:01pm
Hello there!
I'm trying to do some graphics and I'm using vectors
This is a function I'm using to object balls from the screen when
I press the mouse:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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();

    else 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();
  

   else 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();


     else 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();
   
  }
}




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

Mar 27, 2009 at 6:06pm
Im sorry but the word "object "in the 3rd line of question is wrong...
The right word is erase...
sorry
Mar 27, 2009 at 6:28pm
Use std::vector::erase(), however, be warned it will invalidate your iterators to the vector.
Mar 27, 2009 at 6:50pm
What exacty that means?
And how would you access a specific elament with erase()?
Thanks a lot!
Mar 27, 2009 at 7:59pm
Mar 27, 2009 at 9:03pm
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).
Last edited on Mar 27, 2009 at 9:04pm
Topic archived. No new replies allowed.