Why is this vector iterator not incrementable?

前端 未结 8 1209
没有蜡笔的小新
没有蜡笔的小新 2020-12-13 10:41

I\'m trying to delete the vector\'s content and I\'m getting an error - vector iterator is not incrementable, why is that?

This is my destructor:

C         


        
8条回答
  •  轮回少年
    2020-12-13 11:07

    This is not relevant to the original problem posted above, but Google search on the error takes me to this page so I am posting it here for anyone to see.

    I ran into this error message recently and all lines of codes checked out (there was no 'erase' or anything alike; the vector was merely read).

    Eventually, I realized that there is a problem with nested loops.

    For example, consider something like this:

    `for (it=begin(); it!=end();i++)
    {
        for (; it!=end();i++)
        {
        }
    }`
    

    When you are done with the nested loop, it will increment the iterator - and then, the parent loop will increment it again(!), ultimately making the iterator step over the end(). I.e. it would be "end()+1" if there were such a thing. Consequently, the parent loop throws this error at the next check.

    To get around this, I ended up insert this line after the child loop:

    `if (it == vStringList.end()) --it;`
    

    Dirty, but works :D

    I know it may be obvious to some, but I've been scratching my head over this for a while, lol

提交回复
热议问题