Is the statement "vector iterator + offset out of range" generally useful?

This excellently good program does not work 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 an assertion error vector iterator + offset out of range. He fails because that iTo > v.cend()which is harmless here. What is the meaning of a debugger checking the value of an iterator that is not dereferenced?

By the way, 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 tried to make a simple example from more complex real code, where calculating a new iterator value is expensive.

I also understand that you can change the value to change this behavior _ITERATOR_DEBUG_LEVEL, but it creates problems with binary versions of some libraries that are built with default debugging settings.

+4
3

... undefined, end(), . , iTo += 5 iFrom != v.cend() , .

, , 5:

for (auto iFrom = v.cbegin(), iTo = iFrom; iFrom != v.cend(); iFrom = iTo)
{
    iTo += 5;
    cout << *max_element(iFrom, iTo) << '\n';
}
+9

, , "" , VS . , , , , , , , . VS vector<T>::iterator VS 2007.

+1

max_element() . , , . SGI Microsoft :

SGI:

  • [first, last] - .

MSDN:

  • The specified range must be valid; all pointers must be dereferenced, and in each sequence the last position is reachable from the first by incrementing.

If I were in your situation, I would just add a check to check if iTo was really valid as the first step in my cycle. If it is not, set it to the last position in v.

0
source

All Articles