advance iterator in loop

902 Views Asked by At

is there any reason why this works well

vector<CalcToken*>* myVec; //assume this contains CalcToken
for(vector<CalcToken *>::iterator it = myVec->begin() ; it != myVec->end() ; advance(it,1)) {
        cout<< (*it)->toString()<< " ";
    }

and this isnt getting me anything back?(advance(it,2))

for(vector<CalcToken *>::iterator it = myVec->begin() ; it != myVec->end() ; advance(it,2)) {
    cout<< (*it)->toString()<< " ";
}

i want to make a loop that should jump over some elements..., the following isnt working for me either it++,it++ and it+=2.

1

There are 1 best solutions below

1
On

If the vector has an odd number of elements, the advance call will try to advance the iterator past the end of the vector. This is undefined behaviour.

One way to fix it is to use the following modification of the standard advance (I'm limiting to forward direction to save myself work) [untested code]:

template<typename Iterator>
 void limited_advance(Iterator& it, Iterator end, unsigned distance,
                      std::random_access_iterator_tag)
{
  if ((end - it) < distance)
    it += distance;
  else
    it = end;
}

template<typename Iterator>
 void limited_advance(Iterator& it, Iterator end, unsigned distance,
                      ...)
{
  while (it != end && distance > 0)
  {
    ++it;
    --distance;
  }
}

template<typename Iterator>
 void limited_advance(Iterator& it, Iterator end, unsigned distance)
{
  limited_advance(it, end, distance,
                  typename std::iterator_traits<Iterator>::iterator_category());
}

and then replace advance(it,2) with limited_advance(it, myVec->end(), 2).