How can I eliminate an element in a vector if a condition is met

Posted by michael on Stack Overflow See other posts from Stack Overflow or by michael
Published on 2010-03-18T04:57:39Z Indexed on 2010/03/18 5:01 UTC
Read the original article Hit count: 298

Filed under:

Hi,

I have a vector of Rect: vector<Rect> myRecVec;

I would like to remove the ones which are overlapping in the vector:

So I have 2 nested loop like this:

vector<Rect>::iterator iter1 = myRecVec.begin();
   vector<Rect>::iterator iter2 = myRecVec.begin();

    while( iter1 != myRecVec.end() ) {
      Rectangle r1 = *iter1;

      while( iter2 != myRecVec.end() ) {
    Rectangle r2 = *iter1;

    if (r1 != r2) { 
         if (r1.intersects(r2)) {
              // remove r2 from myRectVec
         }

    }
      }
    }

My question is how can I remove r2 from the myRectVect without screwing up both my iterators? Since I am iterating a vector and modifying the vector at the same time? I have thought about putting r2 in a temp rectVect and then remove them from the rectVect later (after the iteration). But how can I skip the ones in this temp rectVect during iteration?

© Stack Overflow or respective owner

Related posts about c++