简体   繁体   中英

Why am I getting a “vector iterator + offset out of range” error?

The following code is causing this error:

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

When I checked the value of searchDepth - depth at the time of the error, it was 0 .

So essentially,

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

is causing this error. (Or not. See comments below.)

To my knowledge the above code should erase the entire vector, which is the desired behavior in this case.

What am I doing wrong?

Try adding parentheses to your expression: bestLine.end() - (searchDepth - depth) . The result is very different if simply evaluated left-to-right.

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

This isn't a coding problem, but a math one.

Problematic math:

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

So, rather than trying to erase (searchDepth - depth) elements, you were trying to erase (searchDepth + depth) elements.

Correct math:

  bestLine.end() - (searchDepth - depth)

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