简体   繁体   中英

C++ Vector iterator error

I've been learning C++ for a week, and here is some code I wrote. I get an error saying that the vector iterator is out of range. The error happens when the value of k and nZeros are both 5, possibleGrid[i][j].size()=4 .

int nZeros = 0;
        for (int k = 0; k < Size; k++)
        {

            if (possibleGrid[i][j][k - nZeros] == 0)
            {
                nZeros++;
                possibleGrid[i][j].erase(possibleGrid[i][j].begin() + k - nZeros); //something here is wrong!!
            }

        }

You're adding 5 to an iterator that only has 4 valid elements. The issue here is the order of evaluation. When the compiler sees possibleGrid[i][j].begin() + k - nZeros , it interprets it as (possibleGrid[i][j].begin() + k) - nZeros ; thus, when k and nZeros are both 5, it first adds 5 to the iterator (rendering it invalid), then subtracts 5 from the now-invalid iterator.

To fix the error, just add parentheses around (k - nZeros) .

I Think if you do below your problem should be solved possibleGrid[i][j].erase(possibleGrid[i][j].begin() + (k - nZeros));

just give a try. :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM