Where does this code dereference an invalid iterator? (C ++)

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 element, I get the error "vector iterator is not reversible." Why am I getting this error and where do I dereference an invalid iterator?

Note. So far, an error exists only when the if () operator is false. I do not know what will happen if the if () statement is correct.

+3
source share
2 answers

What are the sizes of the vectors?

If viral_data has more elements, then antiviral_data, then, since you increase the values ​​of aI and vI at the same speed, aI will go beyond the end of the vI cycle.

Give an example:

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

for, , , j 10, , , 5.

( aI) , :

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

((*aI)->x == (*vI)->x && (*aI)->y == (*vI)->y)

, antiviral_data. antiviral_data.end(), .

+1

Source: https://habr.com/ru/post/1708466/


All Articles