searchDepth - dep...">

Why am I getting "vector iterator + offset out of range" error?

The following code throws this error:

if (bestLine.size() > searchDepth - depth)
    bestLine.erase(bestLine.begin(), bestLine.end() - searchDepth - depth);


When I checked the value searchDepth - depth

at the time of the error it was 0


So essentially

if (bestLine.size() > 0)
    bestLine.erase(bestLine.begin(), bestLine.end());


causes this error. (Or not. See comments below.)

As far as I know, the above code should erase the entire vector, which is the desired behavior in this case.

What am I doing wrong?


source to share

3 answers

Try adding the parentheses to your expression: bestLine.end() - (searchDepth - depth)

. The result is very different if you just evaluate it from left to right.



You check if the value of the bestLine.size () property is greater than searchDepth - depth, but then you select searchDepth + depth. Change the sign before the depth in subtraction: bestLine.erase(bestLine.begin(), bestLine.end() - searchDepth *+* depth);



This is not a coding problem, but a mathematical one.

Problem math:

   bestLine.end() - searchDepth - depth
=> bestLine.end() + (-1) * searchDepth + (-1) * depth
=> bestLine.end() + (-1) * (searchDepth + depth)
=> bestLine.end() - (searchDepth + depth)


So, instead of trying to erase the elements (searchDepth-depth), you tried to erase the elements (searchDepth + depth).

Correct math:

  bestLine.end() - (searchDepth - depth)




All Articles