0

I have c++ code that compiles on Xcode, but when I try to compile it on Visual Studio 2015 I get an error that iterator offset is out of range. Can someone try to help to figure this out:

typename std::vector< HNode<T>* >::iterator ti;

while(temp.size() > 1) {
    std::sort(temp.rbegin(), temp.rend(), HNodePointerCountComparator<T>());

    ti = temp.end();
    ti -= 1;

    temp.push_back(new HNode<T>());
    temp.back()->setCount(temp.back()->getCount() + (*ti)->getCount());
    temp.back()->setLeft(*ti);

    temp.erase(ti);

    ti -= 1; //Debug assertion failed: iterator + offset out of range

    temp.back()->setCount(temp.back()->getCount() + (*ti)->getCount());
    temp.back()->setRight(*ti);

    temp.erase(ti); 
}
2
  • 2
    I have c++ code that compiles -- It is not compilation that is the issue. It is when your program runs that is the issue. Having said this, what exactly on a high-level are you trying to accomplish with this code? It isn't recommended to erase from a vector while iterating over the same vector. Jan 16, 2017 at 0:27
  • Also,the program has a bug that was hidden from you, even if you say it runs in XCode. Be happy that Visual Studio detected it. Jan 16, 2017 at 0:31

2 Answers 2

4

erase invalidates ti, so when you try to modify it afterwords the debug build in VS will flag it.

What you want to do is

ti = temp.erase(ti);

which will have ti refer to the first element after the one you erased. In practice, this means that ti won't change (as that first element will be moved down replacing the one that was erased), but the iterator tracking in debug builds with Visual Studio will be happy with it.

1
  • Also note that push_back may also invalidate ti if it causes a reallocation in the vector.
    – The Dark
    Jan 16, 2017 at 2:19
1

In addition to the other answer provided, this also can invalidate an iterator:

   ti = temp.end();
   ti -= 1;
   temp.push_back(new HNode<T>());

Calling push_back() will result in iterator invalidation. So your ti iterator may not be valid after the call to push_back.

Instead of us giving reasons why you're having these issues, you should state exactly what your goal is in that while loop you've written. I am sure you would get answers that will not only state what you're doing wrong, but also how to write the erasure code correctly.

The best way to not have these issues is to not write a loop that erases items from a std::vector while looping over the vector, and at the same time store iterators within the vector. The way to accomplish this is to use the erase-remove idiom instead of trying to manage iterators and while loops.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.