03-进阶基础/01-数组
跳转到导航
跳转到搜索
一维数组
数组是一组相同类型的变量,可以通过下标访问。
定义数组
int a[100]; // 定义 100 个 int 变量:a[0] ~ a[99]
int b[100] = {0}; // 定义并全部初始化为 0
int c[] = {1, 2, 3, 4, 5}; // 自动推断大小
访问数组
通过下标(从 [math]\displaystyle{ 0 }[/math] 开始)访问数组元素:
a[0] = 1;
cout << a[0];
数组越界
访问的下标必须在定义范围内。例如 int a[100]; 只能访问 a[0] 到 a[99]。
越界访问会导致不可预期的结果(RE / WA),是非常常见的错误。
数组遍历
// 使用范围 for(C++11 起)
for (int x : a)
cout << x << " ";
// 使用下标遍历
for (int i = 0; i < n; i++)
cout << a[i] << " ";
权值数组(计数数组)
用数组下标表示值,数组值表示出现次数:
int cnt[1005] = {0};
for (int i = 1; i <= n; i++)
{
int x;
cin >> x;
cnt[x]++; // x 出现了,计数加一
}
常用于:统计出现次数、桶排序、判断是否出现过。
数组初始化的注意事项
- 定义在全局(所有函数外面)的数组会自动初始化为 [math]\displaystyle{ 0 }[/math]
- 定义在局部(函数内部)的数组如果是 int a[100]; 则为随机值
多维数组
二维数组
int a[100][100]; // 100 行 100 列的二维数组
int b[3][4] = { // 定义并初始化
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
};
访问:a[i][j],其中 [math]\displaystyle{ i }[/math] 为行号,[math]\displaystyle{ j }[/math] 为列号。
// 二维数组遍历
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
cout << a[i][j] << " ";
cout << "\n";
}
三维及更高维
int a[10][10][10]; // 三维数组