数组
数组是用于存储相同类型数据的集合。
定义和初始化
Section titled “定义和初始化”// 定义并初始化int arr[5] = {1, 2, 3, 4, 5};
// 定义时自动推断大小int arr2[] = {10, 20, 30};
// 定义后逐个赋值int arr3[3];arr3[0] = 100;arr3[1] = 200;arr3[2] = 300;int arr[5] = {10, 20, 30, 40, 50};
cout << arr[0] << endl; // 输出第一个元素:10cout << arr[2] << endl; // 输出第三个元素:30cout << arr[4] << endl; // 输出最后一个元素:50int arr[5] = {1, 2, 3, 4, 5};
// 使用 for 循环for (int i = 0; i < 5; i++) { cout << arr[i] << " ";}cout << endl;
// 使用基于范围的 for 循环(C++11)for (int num : arr) { cout << num << " ";}cout << endl;// 3 行 4 列的二维数组int matrix[3][4];
// 初始化int grid[2][3] = { {1, 2, 3}, {4, 5, 6}};int grid[2][3] = { {1, 2, 3}, {4, 5, 6}};
cout << grid[0][0] << endl; // 输出:1cout << grid[1][2] << endl; // 输出:6遍历二维数组
Section titled “遍历二维数组”int grid[2][3] = { {1, 2, 3}, {4, 5, 6}};
for (int i = 0; i < 2; i++) { for (int j = 0; j < 3; j++) { cout << grid[i][j] << " "; } cout << endl;}int arr[5] = {1, 2, 3, 4, 5};int sum = 0;
for (int i = 0; i < 5; i++) { sum += arr[i];}
cout << "总和: " << sum << endl;int arr[5] = {3, 7, 2, 9, 1};int maxVal = arr[0];
for (int i = 1; i < 5; i++) { if (arr[i] > maxVal) { maxVal = arr[i]; }}
cout << "最大值: " << maxVal << endl;- 数组越界 - 访问不存在的索引会导致未定义行为
- 未初始化 - 数组元素默认是随机值
- 大小固定 - 数组大小在编译时确定,不能动态改变