简体   繁体   English

C ++向量迭代器错误

[英]C++ Vector iterator error

I've been learning C++ for a week, and here is some code I wrote. 我已经学习C ++了一个星期,这是我写的一些代码。 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 . knZeros的值均为5时,会发生错误, possibleGrid[i][j].size()=4 nZeros 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. 您要将5加到仅包含4个有效元素的迭代器中。 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 ; 当编译器看到possibleGrid[i][j].begin() + k - nZeros ,它将其解释为(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. 因此,当knZeros均为5时,它首先将5加到迭代器上(使其无效),然后从现在无效的迭代器中减去5。

To fix the error, just add parentheses around (k - nZeros) . 要解决该错误,只需在(k - nZeros)周围加上括号。

I Think if you do below your problem should be solved possibleGrid[i][j].erase(possibleGrid[i][j].begin() + (k - nZeros)); 我认为如果您在下面做您的问题,则应该解决possibleGrid [i] [j] .erase(possibleGrid [i] [j] .begin()+(k-nZeros));

just give a try. 试一试。 :) :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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