C++程序遍历数组中的每个元素
数组是一种称为线性顺序数据结构的数据结构,用于在一系列内存区域中存储同类数据。与其他数据结构一样,数组需要具备某些特性才能有效地插入、删除、遍历和更新元素。我们 C++ 中的数组是静态的。此外,C++ 提供了一些动态数组结构。静态数组最多可以存储 Z 个元素。并且目前其中有 n 个元素。在本文中,我们将了解如何使用 C++ 遍历数组中存在的全部元素。
通过示例理解概念
Given array A = [10, 14, 65, 85, 96, 12, 35, 74, 69] Read all elements one by one 10 14 65 85 96 12 35 74 69
要遍历数组中的所有元素,我们可以简单地运行一个循环,依次访问索引并显示数组的内容。除了这种方法之外,没有其他更简单的方法。因此,算法也很简单,如下所示。
算法
获取大小为 n 的数组 A
对于索引 i 从 0 到 n - 1,执行以下操作
显示 A[ i ]
结束循环
示例
#include <iostream>
# define Z 50
using namespace std;
void displayArr(int arr[], int n){
for( int i = 0; i < n; i++ ){
cout << "Index: " << i << " Element: " << arr[ i ] << endl;
}
}
int main() {
int arr[ Z ] = {57, 10, 14, 19, 86, 52, 32, 14, 76, 65, 32, 14};
int n = 12;
cout << "Array elements: " << endl;
displayArr( arr, n );
}
输出
Array elements: Index: 0 Element: 57 Index: 1 Element: 10 Index: 2 Element: 14 Index: 3 Element: 19 Index: 4 Element: 86 Index: 5 Element: 52 Index: 6 Element: 32 Index: 7 Element: 14 Index: 8 Element: 76 Index: 9 Element: 65 Index: 10 Element: 32 Index: 11 Element: 14
使用向量迭代器
与之前的静态数组方法不同,我们可以使用向量。向量是动态数组。动态数组可以在需要时增加其大小。我们也可以对向量使用与之前相同的方法。但是还有另一种更好的方法,它使用迭代器类。迭代器也随 C++ STL 一起提供。让我们看看使用迭代器访问向量元素的代码。
示例
#include <iostream>
#include <vector>
# define Z 50
using namespace std;
void displayArr( vector<int> v ){
vector<int>::iterator it;
for( it = v.begin(); it != v.end() ; it++ ){
cout << "Index: " << (it - v.begin()) << " Element: " << *it << endl;
}
}
int main() {
vector<int> arr = {57, 10, 14, 19, 86, 52, 32, 14, 76, 65, 32, 14};
cout << "Array elements: " << endl;
displayArr( arr );
}
输出
Array elements: Index: 0 Element: 57 Index: 1 Element: 10 Index: 2 Element: 14 Index: 3 Element: 19 Index: 4 Element: 86 Index: 5 Element: 52 Index: 6 Element: 32 Index: 7 Element: 14 Index: 8 Element: 76 Index: 9 Element: 65 Index: 10 Element: 32 Index: 11 Element: 14
在这种方法中,创建了一个迭代器对象,该对象被分配给 v.begin(),它是向量的起始位置。当它不是 v.end() 时,打印 (it – v.begin()),这将返回元素的索引(因为“it”是当前元素的地址,而 v.begin() 是第一个元素的地址。因此,差值就是索引)。可以使用 *it 访问“it”的值。
使用向量和 for-each 循环
此方法与上面显示的任何其他方法没有区别。唯一的区别在于循环。较新的 C++ 版本支持 for-each 循环,在该循环中,我们隐式地遍历元素,而不是通过索引遍历。让我们看看代码示例以更好地理解。
示例
#include <iostream>
#include <vector>
# define Z 50
using namespace std;
void displayArr( vector<int> v ){
for( int e : v ){
cout << "Element: " << e << endl;
}
}
int main() {
vector<int> arr = {57, 10, 14, 19, 86, 52, 32, 14, 76, 65, 32, 14};
cout << "Array elements: " << endl;
displayArr( arr );
}
输出
Array elements: Element: 57 Element: 10 Element: 14 Element: 19 Element: 86 Element: 52 Element: 32 Element: 14 Element: 76 Element: 65 Element: 32 Element: 14
结论
在本文中,我们看到了两种不同的方法来读取数组中的所有元素。第一种是使用静态数组,我们通过访问索引逐个遍历每个元素。下一种方法是使用向量迭代器。向量迭代器就像列表、映射、集合等任何其他迭代器。可以使用循环逐个获取元素。在 C++ 的后续版本中,我们可以获得另一个有趣的 for 循环,即 for-each 循环。这不需要额外的索引或指针引用。它在本文档的最后一个示例中显示。
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP