views:

330

answers:

2

I have a loop

for(aI = antiviral_data.begin(); aI != antiviral_data.end();)
{
 for(vI = viral_data.begin(); vI != viral_data.end();)
 {
  if((*aI)->x == (*vI)->x && (*aI)->y == (*vI)->y)
  {
   vI = viral_data.erase(vI);
   aI = antiviral_data.erase(aI);
  }
  else
  {
   vI++;
   aI++;
  }
 }
}

But when ever antiviral_data contains an item, I get an error "vector iterator not dereferencable." Why am I geting this error and where am I dereferencing an invalid iterator?

NB: So far th error only occurs when the if() statement is false. I don't know what happens if the if() statement is true.

+7  A: 

What are the sizes of the vectors?

If viral_data has more elements then antiviral_data, then, since you increment aI and vI at the same rate, aI would go out of bounds before the vI loop would end.

Take a short example here:

for(int i = 0; i < 5;)
{
    for(int j = 0; j < 10;)
    {
        i++;
        j++;
    }
}

If you go over the for loops, you'll notice that the inner loop will not end until both j and i are 10, but according to your outer loop, i should not be more then 5.

You'll want to increment i (or in your case, aI) in the outer loop like so:

for(int i = 0; i < 5;)
{
    for(int j = 0; j < 10;)
    {
        j++;
    }
    i++;
}
DeadHead
vI is always two, aI starts out at 0. Thanks
Keand64
A: 

The dereferencing is happening at "((*aI)->x == (*vI)->x && (*aI)->y == (*vI)->y)" and it occurs when that statement is true for the last element in the antiviral_data list. In that case on the next iteration of the inner for loop you will be dereferencing antiviral_data.end() which is not allowed.

Daniel