C++数组迭代程序
数组是在内存中连续存储的相同类型数据的集合。为了访问或寻址数组,我们使用数组的起始地址。数组具有索引,我们可以使用索引访问数组的元素。在本文中,我们将介绍迭代数组的方法。这意味着访问数组中存在的元素。
使用for循环
迭代数组最常用的方法是使用for循环。在下面的示例中,我们将使用for循环遍历数组。需要注意的是,我们需要知道数组的大小。
语法
for ( init; condition; increment ) {
statement(s);
}
算法
- 输入大小为n的数组arr。
- 对于 i := 0 到 i := n,执行
- 打印 (arr[i])
示例
#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
使用while循环
类似于for循环,我们可以使用while循环遍历数组。在这种情况下,也必须知道或确定数组的大小。
语法
while(condition) {
statement(s);
}
算法
- 输入大小为n的数组arr。
- i := 0
- 当 i < n 时,执行
- 打印 (arr[i])
- i := i + 1
示例
#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
使用forEach循环
我们还可以使用现代的forEach循环来遍历数组中的元素。这种方法的主要优点是我们不需要知道数组的大小。
语法
for (datatype val : array_name) {
statements
}
算法
- 输入大小为n的数组arr。
- 对于每个元素 val in arr,执行
- 打印(val)
示例
#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++中迭代数组的各种方法。前两种方法的主要缺点是必须预先知道数组的大小,但是如果我们使用forEach循环,则可以解决这个问题。forEach循环支持所有STL容器,并且更易于使用。
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP