- // 27 - 二维数组. cpp: 定义控制台应用程序的入口点.
- //
- #include "stdafx.h"
- #include <iostream>
- #include <climits>
- #include <array>
- #include <string>
- using namespace std;
- int main()
- {
- int scores[5] = { 34,6,34,835,3 }; // 一维数组
- int scores2[4][5] = { // 可以理解为长度为 4 的数组, 每个数组中又包含了长度为 5 的数组, 数组中包含数组.
- // 类似树状图, 分为上下两层. 第一层是第一维, 从第一层中分支出第二层, 第二维.
- {123,235,4,62,321},
- {73,132,6,833,452},
- {3426,78,421,3,6742},
- {34,6,9,13,6},
- };
- // 如何访问二维数组?
- cout <<scores2[1][1] << endl; // 访问第二行第二列数组. 132
- // 如何遍历二维数组呢? 有两个索引. 使用循环嵌套.
- for (int i = 0; i < 5; i++)
- {
- for (int j = 0; j < 6; j++)
- {
- cout << "i:" << i <<""<<"j" << j << endl;
- }
- }
- // 方式 1, 先遍历行 (一层), 后遍历列 (二层).
- for (int i = 0; i < 4; i++)
- {
- for (int j = 0; j < 5; j++)
- {
- cout << scores2[i][j] << " ";
- }
- cout << endl;
- }
- // 方式 2, 先遍历列 (二层), 后遍历行 (一层).
- for (int i = 0; i < 5; i++) //i 代表第二层的位置
- {
- for (int j=0;j<4;j++) //j 代表第一层的位置
- {
- cout << scores2[j][i] << " ";
- }
- cout << endl;
- }
- int t;
- cin>> t;
- return 0;
- }
来源: http://www.bubuko.com/infodetail-2694370.html