首页 > 编程知识 正文

for循环遍历数组,数组循环语句

时间:2023-05-04 19:02:12 阅读:11699 作者:3066

原文地址: http://www.geeksforgeeks.org/circular-array /

如果数组中最后一个元素的下一个元素是整个数组中的第一个元素,则该数组被认为是循环数组。 循环数组一般也在队列中实现。

例题:

假设圆桌上坐了n个人。 他们的名字是a、b、c、d、……。 给定名字,我们就打印出n个座位的顺序,从这个给定的人开始。

例如,假设有六个ABCDEF,并且知道d。 围着圆桌从d开始就是缉毒组。

一个简单的方法是创建2*n的空间。 n是数组的长度。 例如,为六个人创建一个名为ABCDEFABCDEF的附属数组。

现在,您可以打印任何索引的所有从开头的元素。 例如打印: ABC DEFABCDEF。

以下是上述方法的简单实现。

//cppprogramtodemonstrateuseofcircular//arrayusingextramemoryspace # include bits/stdc.husingnamespacestd; void打印(chara )、int n、int ind )//createanauxiliaryarrayoftwicesize.charb ) )2*n ) ); //copya [ ] tob [ ] twotimesfor (inti=0; i n; I ) b(I )=b ) nI )=a(I ); //printfromind-thindexto(nI ) thindex.for(intI=ind; i n ind; I ) cout b[i] '; (}//驱动程序代码int main ) ) chara ()=(a )、(b )、(c )、(d )、(e )、(f ); intn=sizeof(a )/sizeof ) a[0]; 打印(a,n,3 ); 返回0; }输出:

名为DEFABC的方法需要的时间是o(n ),但需要额外的o(n )空间。

另一种高效的方法是就地处理循环序列。 仔细看看数组,就会发现第n个下标之后的索引在使用mod运算符时总是从0开始,这样就可以很容易地访问循环列表中的元素。 从第I个下标到第n个下标(I ) %n允许mod遍历循环数组,而不需要额外的空格。

//cpprogramtodemonstratetheuseofcircular//arraywithoutusingextramemoryspace # include bits/stdc.husingnamespacestd; //functiontoprintcircularliststarting//fromgivenindexind.void print (chara [ ],int n,int ind ) )/printfromind-tro I ) couta () I%n ) '; //drivercodetochecktheabovefunctionintmain ((chara )=) a )、(b )、(c )、(d )、(e )、(f ); intn=sizeof(a )/sizeof ) a[0]; 打印(a,n,3 ); 返回0; }输出:

德夫ABc

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。