数组 是一种 线性结构, 在内存中是一段 连续的内存 存储空间存储。 那么 如何实现循环的数组呢?
什么是循环数组? 循环数组 就是 数组的头尾是相连的。
假如有一个数组 [3,7,2,9,1,5] , 形成的环形数组 如下图:
用代码实现,如下:
vector<int> num = {3,7,2,9,1,5};
int size = num.size();
int i = 0;
while (true)
{
cout << " " << num[i % size];
i++;
}
使用 % 求余 的技巧,来实现 持续遍历循环数组。
如果想 遍历 一圈该循环数组,代码如下:
#include <iostream>
#include <vector>
using std::vector;
using std::cout;
using std::endl;
int main()
{
vector<int> num = {3,7,2,9,1,5};
int size = num.size();
for(int index=0; index<2*size;index++)
{
cout <<" "<< num[index % size] ;
}
return 0;
}
执行的结果: