bhan
bhan

Reputation: 2499

Stopping an iterator before the end

I have an iterator p and a vertex curvePoints:

for (p = curvePoints.begin(); p != curvePoints.end(); p++) {
  p->x = (1 - u) * p->x + u * (p+1)->x;
  p->y = (1 - u) * p->y + u * (p+1)->y;
}

Right now the loops use the value of the next indexed object; how can I guarantee that that next value exists. In other words, how can I make the loop condition something like (p+1) != curvePoints.end() or p != curvePoints.end() - 1.

Upvotes: 3

Views: 5179

Answers (5)

Dietmar Kühl
Dietmar Kühl

Reputation: 154035

The way I would do it is to not compare against end() unless the sequence is empty. If the sequence is non-empty you would compare against end() - 1 and probably cache the value:

for (auto p(points.begin()), 
          end(c.end() - (c.empty()? 0, 1));
     p != end; ++p) {
    ...
}

Upvotes: 0

krlmlr
krlmlr

Reputation: 25484

You can cache and reuse the value of p-s successor:

auto p = curvePoints.begin();
if (p != curvePoints.end()) {
  auto pn = p; ++pn;
  for (; pn != curvePoints.end(); p = pn, ++pn) {
    ... // use pn instead of (p+1)
  }
}

NB: Pre-increment is preferable for iterators.

Upvotes: 1

JNo
JNo

Reputation: 457

 for (p = curvePoints.begin(); p < curvePoints.end(); p++) {
          p->x = (1 - u) * p->x + u * (p+1)->x;
          p->y = (1 - u) * p->y + u * (p+1)->y;

Upvotes: -2

tomahh
tomahh

Reputation: 13661

You can use std::distance(p, curvePoints.end()) > 1 as you condition.

http://www.cplusplus.com/reference/std/iterator/distance/

Upvotes: 3

David Schwartz
David Schwartz

Reputation: 182875

How about changing p != curvePoints.end() to
(p != curvePoints.end()) && ((p + 1) != curvePoints.end())?

Upvotes: 1

Related Questions