How do safely add or subtract a number from an iterator?

Mar 7, 2013 at 4:54am
Hi everyone,

Suppose I have an iterator and I want to increment the iterator by, say, 5. Without adding 1 to the iterator and checking it != vec.end() at every step, is it possible for me to simply add 5 to it and then check if I've gone to far? Same goes for subtracting 5, is this possible?
Mar 7, 2013 at 4:59am
Mar 7, 2013 at 5:09am
What type of iterator are you talking about? Random access or Bidirectional?
Mar 7, 2013 at 6:02am
Not really sure, this one:

vector<Double>::iterator = it;
Mar 7, 2013 at 6:07am
IdeasMan: I don't know what the iterator to the second location will be, only the distance. So I could use something like this:

1
2
int distance = 5;
advance (it,distance); // if I don't know where "it" is sitting, how will I know if this works? 


But I'll have no way of knowing if that will work or not. I guess I'd have to do something like this:

1
2
3
4
5
6
7
int distance = 5;
if (distance > 0 && distance(it,vec.end()) > distance)
  advance (it,distance);
else if (distance < 0 && distance(vec.begin(),it) >= distance)
  advance(it,distance);
else
  throw hissyfit;


Is that the only option I've got?
Mar 7, 2013 at 6:32am
std::distance works out the distance between 2 iterators - you query was about seeing whether adding or subtracting an arbitrary number would go out of bounds.

So compare the distance from your iterator to the end, is less than the arbitrary number.

1
2
3
4
5
6
7
8
size_t Amount = 5;

if (std::distance(it, vec.end) > Amount) {
       advance(it,Amount);
}
else {
 // throw ControlledHissyFit;
}


HTH
Topic archived. No new replies allowed.