首页  >  文章  >  后端开发  >  C++程序迭代数组

C++程序迭代数组

WBOY
WBOY转载
2023-09-01 17:09:17590浏览

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);
}

算法

  • 在大小为n的数组arr中输入数据。
  • 对于 i := 0 到 i := n,执行:
    • 打印(arr[i])

Example

的中文翻译为:

示例

#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
  • while i
  • 打印(arr[i])
  • i := i + 1

Example

的中文翻译为:

示例

#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循环

我们还可以使用现代的for-each循环来遍历数组中的元素 主要的优点是我们不需要知道数组的大小。

语法

for (datatype val : array_name) {
   statements
}

算法

  • 在大小为n的数组arr中输入数据。
  • 对于数组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++程序迭代数组的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文转载于:tutorialspoint.com。如有侵权,请联系admin@php.cn删除