This perfectly good program fails in debug mode in Visual Studio 2013:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
void main()
{
vector<int> v = {3, 1, 4, 1, 5, 9, 2, 6, 5, 3};
for (auto iFrom = v.cbegin(), iTo = iFrom+5; iFrom != v.cend(); iFrom = iTo, iTo += 5)
cout << *max_element(iFrom, iTo) << '\n';
}
with vector iterator + offset out of range
assertion failure. It fails because iTo > v.cend()
, which is harmless here. What is the point of debugger testing the value of iterator, which is not being dereferenced?
BTW, I know that I can rewrite the loop above as:
for (auto i = v.cbegin(); i != v.cend(); i += 5)
cout << *max_element(i, i+5) << '\n';
but I was trying to make a simple example out of a piece of more complex real-life code, where calculating the new iterator value is computationally expensive.
I also realize that one can change _ITERATOR_DEBUG_LEVEL
value to affect this behavior, but it creates problems with binary versions of some libraries, which are built with default debug settings.