# **二維/多維陣列**
### 2020 資訊之芽
#### 2020/3/28
#### 實習生 袁紹奇
---
## 什麼是維???!

----
## 對應到的是
| 維度 | 對應到... |
| ---- | ------------- |
| 零維 | int a |
| 一維 | int a[10] |
| 二維 | int a[10][10] |
| ... | ... |
---
## 二維陣列宣告
* 型態 名稱 [大小][大小]... (初始化)
```cpp
int W[5][4]; // 裡面裝垃圾值
int H[2][3] = {{1, 2, 3}, {4, 5}}; // H[1][2] == 0
int O[2][3] = {}; // 全部裝零
```
----
## 二維陣列宣告
* 也可以不要寫最前面的大小(如果有初始化)
```cpp
int X[][2] = {{1, 2}, {3, 4}}; // 最前面的大小是2
int I[][2] = {{1, 2}, {3}}; // 同上,I[1][1] == 0
```
----
## 請搭配for先生使用
```cpp
int winnie[10][20];
for(int i = 0; i < 10; i++){
for(int j = 0; j < 20; j++)
cin >> winnie[i][j];
}
```
----

---
## 注意!
* 索引值從0開始
* 索引值只能是整數
* 也可以用變數當索引
* 讀到記憶體外就會RE吃到飽
----
[視覺化效果](http://pythontutor.com/visualize.html#mode=edit)
----
```cpp
#include <iostream>
using namespace std;
int main(){
int H[2][3] = {{1, 2, 3}, {4, 5}};
for(int i = 0; i < 2; i++){
for(int j = 0; j < 3; j++)
cout << H[i][j] << ' ';
cout << endl;
}
}
```
---
## 多維陣列
----
## 多維陣列宣告
```cpp
int X[][2][2] = {{{1, 2}, {3, 4}}, {{1, 2}, {3, 4}}}
// 最前面的大小會是2
int I[][2][2] = {{{1, 1}, {1}}, {{1}}}
// 最前面的大小也是2, 其他值為0
```
---
## 注意!
#### 陣列不能互相指定,比較
```cpp
int C[3][3] = {};
int o[3][3];
o = C; //compile error
int V[3][3] = {};
if(C == V) // 不等於
cout << "impossible" << endl;
```
---
[練習](https://neoj.sprout.tw/problem/214/)
----
## Solution
```cpp
#include <iostream>
#define size 100
using namespace std;
int main(){
int n, m;
int mine[size][size] = {}; // mine[n][m]
cin >> n >> m;
for(int i = 0; i < n; i++){
for(int j = 0; j < m; j++)
cin >> mine[i][j];
}
int dx[8] = {1, 1, 0, -1, -1, -1, 0, 1};
int dy[8] = {0, -1, -1, -1, 0, 1, 1, 1};
int res[size][size] = {}; // the answer
for(int i = 0; i < n; i++){
for(int j = 0; j < m; j++){
for(int dir = 0; dir < 8; dir++){
if(j+dx[dir]>=0 && j+dx[dir]<m &&
i+dy[dir]>=0 && i+dy[dir]<n){
res[i][j] += (mine[i+dy[dir]][j+dx[dir]] == 1);
}
}
}
}
for(int i = 0; i < n; i++){
for(int j = 0; j < m-1; j++)
cout << res[i][j] << ' ';
cout << res[i][m-1];
cout << endl;
}
}
```
{"metaMigratedAt":"2023-06-15T05:40:20.356Z","metaMigratedFrom":"Content","title":"**二維/多維陣列**","breaks":true,"contributors":"[{\"id\":\"c5aa2397-41e9-4519-9c42-c485a8ba1b50\",\"add\":2724,\"del\":301}]"}