我有一个迭代器p和一个顶点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;
}
现在循环使用下一个索引对象的值;我怎样才能保证下一个值存在。换句话说,如何使循环条件类似(p+1) != curvePoints.end()
或p != curvePoints.end() - 1
。
答案 0 :(得分:1)
如何将p != curvePoints.end()
更改为(p != curvePoints.end()) && ((p + 1) != curvePoints.end())
?
答案 1 :(得分:1)
您可以在条件允许的情况下使用std::distance(p, curvePoints.end()) > 1
。
答案 2 :(得分: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)
}
}
注意:迭代器最好是预增量。
答案 3 :(得分:0)
我这样做的方法是不与end()
进行比较,除非序列为空。如果序列非空,您将与end() - 1
进行比较,并可能缓存值:
for (auto p(points.begin()),
end(c.end() - (c.empty()? 0, 1));
p != end; ++p) {
...
}
答案 4 :(得分:-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;