数组是相同类型的数据在内存中连续存储的。要访问或address an array, we use the starting address of the array. Arrays have indexing, using which寻址数组时,我们使用数组的起始地址。数组具有索引,通过索引可以进行访问我们可以访问数组的元素。在本文中,我们将介绍迭代数组的方法在一个数组上进行操作。这意味着访问数组中存在的元素。
使用for循环
遍历数组最常见的方法是使用for循环。我们使用for循环来在下一个示例中遍历一个数组。需要注意的一点是,我们需要数组的大小这个中的数组。
语法
for ( init; condition; increment ) { statement(s);}
登录后复制
算法
在大小为n的数组arr中输入数据。对于 i := 0 到 i := n,执行:打印(arr[i])
Example
的中文翻译为:
示例
#include #include using namespace std;// displays elements of an array using for loopvoid solve(int arr[], int n){ for(int i = 0; i输出
Values in the array are: 10 5 11 13 14 2 7 65 98 23 45 32 40 88 32登录后复制
使用while循环
与for循环类似,我们可以使用while循环来迭代数组。在这种情况下,也是这样的
数组的大小必须是已知或确定的。
语法
while(condition) { statement(s);}登录后复制
算法
在大小为n的数组arr中输入数据。i := 0while i 打印(arr[i])i := i + 1
Example
的中文翻译为:
示例
#include #include using namespace std;// displays elements of an array using for loopvoid solve(int arr[], int n){ int i = 0; while (i输出
Values in the array are: 10 5 11 13 14 2 7 65 98 23 45 32 40 88 32登录后复制
使用forEach循环
我们还可以使用现代的for-each循环来遍历数组中的元素主要的优点是我们不需要知道数组的大小。
语法
for (datatype val : array_name) { statements}登录后复制
算法
在大小为n的数组arr中输入数据。对于数组arr中的每个元素val,执行以下操作:print(val)
Example
的中文翻译为:
示例
#include #include using namespace std;int main(){ int arr[] = {10, 5, 11, 13, 14, 2, 7, 65, 98, 23, 45, 32, 40, 88, 32}; //using for each loop cout输出
Values in the array are: 10 5 11 13 14 2 7 65 98 23 45 32 40 88 32登录后复制
结论
本文描述了在C++中遍历数组的各种方法。主要方法包括:
drawback of the first two methods is that the size of the array has to be known beforehand,但是如果我们使用for-each循环,这个问题可以得到缓解。for-each循环支持所有的STL容器并且更易于使用。
以上就是C++程序迭代数组的详细内容,更多请关注【创想鸟】其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。
发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2584354.html