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);
}
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.