# 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?

+3

source to share

3 answers

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)
```

+1

source to share