c++ - 在 C++ 中使用迭代器时如何获取循环数?

标签 c++ iterator positioning counter

我正在开发一个应用程序,我在其中绘制了一些图像,如下所示:

void TimeSlice::draw(float fX, float fY) {
list<TimeSliceLevel*>::iterator it = levels.begin();
float level_x = x;
float level_y = y;
while(it != levels.end()) {
    (*it)->draw(level_x,level_y);
    level_y += (*it)->height;
    ++it;
}

虽然这有点不正确。我需要将 TimeSliceLevel* 定位在 X 上。当我 得到一个for(int i = 0; i < slices.size(); ++i)循环,我可以使用 x = i * width .虽然我使用的是迭代器,因为我多次被告知这是一个很好的编程 :> 我想知道迭代器是否有一个“索引”号,我可以用它来计算新的 X 位置? (所以更多的是关于使用迭代器的问题)

亲切的问候, 北河三

最佳答案

它们不会,因为除了从头到尾循环有序的索引列表之外,迭代器还可以用于其他目的。您需要单独跟踪索引并在每次通过时递增它:

list<TimeSliceLevel*>::iterator it;
int index;

for(it = levels.begin(), index = 0; it != levels.end(); ++it, ++index) {
    ...
}

关于c++ - 在 C++ 中使用迭代器时如何获取循环数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3029637/

相关文章:

c++ - vector 模板问题

c++ - 概率和随机数

c++ - 将 std::find() 与反向迭代器一起使用

java - 如何使用 java 8 迭代 JsonArray

c++ - 迭代器,循环导致段错误!为什么循环太多了?

c++ - 在 OpenSSL 1.1.0+ 中,我是否需要使用 CRYPTO 锁定函数来保证线程安全?

c++ - 如何判断(以编程方式)Windows 7 PC 上是否正在使用大字体

html - CSS - 在顶 Angular 设置 div 并使其他 div 围绕它 float

css - Jquerymobile div 在绝对中心

css - IE7中绝对定位限制div的宽度