
数组是相同类型的数据在内存中连续存储的。要访问或 address an array, we use the starting address of the array. Arrays have indexing, using which 寻址数组时,我们使用数组的起始地址。数组具有索引,通过索引可以进行访问 我们可以访问数组的元素。在本文中,我们将介绍迭代数组的方法 在一个数组上进行操作。这意味着访问数组中存在的元素。
for ( init; condition; increment ) {
statement(s);
}
#include <iostream>
#include <set>
using namespace std;
// displays elements of an array using for loop
void 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
与for循环类似,我们可以使用while循环来迭代数组。在这种情况下,也是这样的
数组的大小必须是已知或确定的。
while(condition) {
statement(s);
}
#include <iostream>
#include <set>
using namespace std;
// displays elements of an array using for loop
void 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
for (datatype val : array_name) {
statements
}
#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++程序迭代数组的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号