This snippet searches a vector of integers for items divisible by 3 using an iterator. Then it writes the number to a file and erases that number from the vector.
The problem is that when the program encounters a value divisible by 3 it deletes it from the vector and then crashes.
Here is the error.
This error only occurs when trying to compile the program in debug version of VC++. The program works fine if it is built as a release version.
This is because the Debug version does more runtime checks to catch errors like this. The error is in fact occuring in Release as well -- however it will only happen under the right circumstances (ie: if the vector needs to reallocate the buffer somewhere else due to a resize). It's much easier to detect bugs like this when Debug complains rather than waiting for your program to crash under just the wrong circumstances (leaving you wondering why your program only crashes sometimes and works just fine other times).
One possible solution here is to use erase()'s return value:
Just as an FYI... if you have a large vector, repeat erases will be hideously expensive. (I suspect you don't; but just to keep in mind, erases from anywhere but the end in a vector are very expensive. Consider using a deque instead).
And for that matter, although you can implement what you want in 1 line of code using boost::lambda, remove_if, and list.erase(), that is no more efficient than Disch's algorithm (it's just less typing if you are familiar enough with boost::lambda to get it right on the first try--which is no easy task).