基于这些问题: Is there a standard cyclic iterator in C++,Iterators for circular structures和Easiest way to make a cyclic iterator (circulator)? 我假设在STL中没有循环迭代器,但后来我发现下面的代码实现了像迭代器一样的循环, 我没有找到任何描述这种行为的文档,所以我决定在这里确认一下。
#include <iostream>
#include <list>
using namespace std;
int main () {
list<int> firstlist {1, 2, 3, 4, 5};
auto it = firstlist.begin();
for ( int i = 0; i < 20; i++ ) {
if(it == firstlist.end()) {
cout << "==end==" << endl;;
it++;
}
cout << i << ": " << *it++ << endl;
}
return 0;
}
输出:
0: 1
1: 2
2: 3
3: 4
4: 5
==end==
5: 1
6: 2
7: 3
8: 4
9: 5
==end==
10: 1
11: 2
12: 3
13: 4
14: 5
==end==
15: 1
16: 2
17: 3
18: 4
19: 5
以下是执行链接:code