您好,欢迎访问一九零五行业门户网

C++程序迭代数组

数组是相同类型的数据在内存中连续存储的。要访问或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);}
算法<li>在大小为n的数组arr中输入数据。</li>对于 i := 0 到 i := n,执行:打印(arr[i])example的中文翻译为:示例#include <iostream>#include <set>using namespace std;// displays elements of an array using for loopvoid solve(int arr[], int n){ for(int i = 0; i < n; i++) { cout << arr[i] << ' '; } cout << endl;}int main(){ int arr[] = {10, 5, 11, 13, 14, 2, 7, 65, 98, 23, 45, 32, 40, 88, 32}; int n = 15; cout << values in the array are: ; solve(arr, n); return 0;}
输出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);}
算法<li>在大小为n的数组arr中输入数据。</li>i := 0while i < n, do:打印(arr[i])i := i + 1example的中文翻译为:示例#include <iostream>#include <set>using namespace std;// displays elements of an array using for loopvoid solve(int arr[], int n){ int i = 0; while (i < n) { cout << arr[i] << ' '; i++; } cout << endl;}int main(){ int arr[] = {10, 5, 11, 13, 14, 2, 7, 65, 98, 23, 45, 32, 40, 88, 32}; int n = 15; cout << values in the array are: ; solve(arr, n); return 0;}
输出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}
算法<li>在大小为n的数组arr中输入数据。</li>对于数组arr中的每个元素val,执行以下操作:print(val)example的中文翻译为:示例#include <iostream>#include <set>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: ; for(int val : arr) { cout << val << ' '; } cout << endl; return 0;}
输出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++程序迭代数组的详细内容。
其它类似信息

推荐信息