3

我有一个迭代器 p 和一个顶点曲线点:

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

现在循环使用下一个索引对象的值;我如何保证下一个值存在。换句话说,我怎样才能使循环条件类似于(p+1) != curvePoints.end()or p != curvePoints.end() - 1

4

5 回答 5

3

您可以std::distance(p, curvePoints.end()) > 1根据情况使用。

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

于 2012-10-05T10:51:11.503 回答
1

您可以缓存和重用p-s 后继的值:

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

注意:对于迭代器来说,预增量是更可取的。

于 2012-10-05T10:58:42.687 回答
1

换成怎么p != curvePoints.end()
(p != curvePoints.end()) && ((p + 1) != curvePoints.end())

于 2012-10-05T10:50:17.180 回答
0

我会这样做的方式是不进行比较,end()除非序列为空。如果序列非空,您将比较end() - 1并可能缓存该值:

for (auto p(points.begin()), 
          end(c.end() - (c.empty()? 0, 1));
     p != end; ++p) {
    ...
}
于 2012-10-05T13:08:55.287 回答
-1
 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;
于 2012-10-05T10:52:12.580 回答