44 lines
1.0 KiB
C++
44 lines
1.0 KiB
C++
|
// 请完成以下程序的代码,实现数组的循环迭代
|
||
|
#include <iostream>
|
||
|
|
||
|
using namespace std;
|
||
|
|
||
|
template <typename T>
|
||
|
class Iterator
|
||
|
{
|
||
|
public:
|
||
|
T *data;
|
||
|
int size;
|
||
|
int currentIndex;
|
||
|
|
||
|
public:
|
||
|
Iterator(T *d, int s) : data(d), size(s), currentIndex(0) {}
|
||
|
T getCurrent() // 获取当前元素
|
||
|
{
|
||
|
return data[currentIndex];
|
||
|
}
|
||
|
void next() // 迭代器前进的代码
|
||
|
{
|
||
|
currentIndex = (currentIndex + 1) % size; // 对 size 取余用于循环
|
||
|
}
|
||
|
void previous() // 迭代器后退的代码
|
||
|
{
|
||
|
currentIndex = (currentIndex - 1 + size) % size; // + size 用于防止负数,对 size 取余用于循环
|
||
|
}
|
||
|
};
|
||
|
|
||
|
int main()
|
||
|
{
|
||
|
int *p = new int[5]{1, 2, 3, 4, 5}; // 创建数组
|
||
|
Iterator<int> it(p, 5); // 创建迭代器对象
|
||
|
|
||
|
int cnt = 0; // 计数器,用于控制循环次数
|
||
|
while (cnt++ < 5)
|
||
|
{
|
||
|
cout << it.getCurrent() << endl; // 输出当前元素
|
||
|
it.next(); // 迭代器前进
|
||
|
}
|
||
|
|
||
|
return 0;
|
||
|
}
|