'Why C++ throws an out of range error here?

I really cannot find the reason why here a "cannot seek vector iterator after end" error occurs. I cannot show the whole code but I think that this part should be enough:

qDebug() << Pun.size() << ", " << 2*pos - counter;
Pun.erase(Pun.begin() + 2*pos - counter); //the error seems to happen here
qDebug() << "B";
Pun.erase(Pun.begin() + 2*pos - counter);
counter += 2;

When I run my code, the last what is printed is "4, 1" and the "B" is not printed so it has to be in the line above but it can't if Pun.size() is 4 and 2*pos - counter is 1.

Maybe this helps: This is part of a big algorithm for a special problem and I run into this problem when I tested the program on a lot of instances. I traced down the error to a special instance and the weird thing is that when I run the algorithm the first time this error doesn't occur but when it's done the second time it somehow does....

Any hint would be really helpful...



Solution 1:[1]

Operator precedence problems -- + and - are the same precedence (and are left-recursive), so your erase call is really

Pun.erase((Pun.begin() + 2*pos) - counter);

which probably tries to advance well past the end of Pun, causing it to throw an exception. I'm assuming here Pun is some custom sequence type that does bounds checking (ie, not std::vector). You want

Pun.erase(Pun.begin() + (2*pos - counter));

Solution 2:[2]

you mean

Pun.erase(Pun.begin() + (2*pos - counter)); 

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Chris Dodd
Solution 2 pm100