mardi 27 novembre 2018

Using iterators in nested loop through two vectors two match elements and erase from the vectors

I wanted to use the following loops to match elements from two vectors and then delete them from the vectors:

for(auto it1=left_unprocessed_event_arrays.begin(); it1!=left_unprocessed_event_arrays.end(); ++it1){
  for(auto it2=right_unprocessed_event_arrays.begin(); it2!=right_unprocessed_event_arrays.end(); ++it2){
    if(it1->header.stamp.nsec==it2->header.stamp.nsec){
      matching_event_arrays.push_back({*it1,*it2});
      left_unprocessed_event_arrays.erase(it1);
      right_unprocessed_event_arrays.erase(it2);
    }
  }
}

I then realised I couldn't do it like this, because using the erase() is making the iterators invalid.
Searching a solution brought me to this. Here someone suggests using the pointer that is returned by erase(), and then incrementing the iterator in the else-bracket. But When I increment only in the innerloop, it won't correctly go through the outer-loop. I'm struggling to see how I can make this work for my nested loop.
So my question is: How can I implement the solution of the linked answer for a nested loop? Or if there is another/better solution: what's that?

Aucun commentaire:

Enregistrer un commentaire