Multidimensional arrays have values in rows and columns.
Built-in arrays
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
|
int init_arr[3][3] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} };
int auto_num[][2] = { {1, 2}, {3, 4} };
for (auto i = 0; i < sizeof(init_arr) / sizeof(*init_arr); ++i) { for (auto j = 0; j < sizeof(init_arr[i]) / sizeof(int); ++j) { cout << init_arr[i][j] << " "; } cout << "\n"; }
|
array class
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| #include <array>
array<array<int, 3>, 2> arr;
arr.fill({1,2,3});
for (auto i = 0; i < arr.size(); ++i) { for (auto j = 0; j < arr[0].size(); ++j) { cout << arr.at(i).at(j) << " "; } cout << "\n"; }
|
vector class
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
|
vector<vector<int>> vec;
int num = 1; for (auto i = 0; i < 3; ++i) { vector<int> temp; for (auto j = 0; j < 3; ++j) { temp.push_back(num++); } vec.push_back(temp); }
for (auto i = 0; i < 3; ++i) { for (auto j = 0; j < 3; ++j) { cout << vec.at(i).at(j) << "\n"; } }
|
Jagged arrays
Jagged arrays are array of variable length arrays like
1 2 3 4
| | 1 2 | | 4 1 3 | | 5 | | 1 4 5 6 7 |
|
1 2 3 4 5 6 7 8 9 10
|
int **jagged_arr = new int*[3];
array<vector<int>, 3> jag_3_n;
vector<vector<int>> jag_n_n;
|