13. 通用二维数组制造函数

题目:

 为程序make_2d_array 编写一个通用型算法,它的第三个参数不是整数 col_number,而是一维数组row_size。它创建一个二维数组,第 i 行的列数是 row_size [ i ]。

思路:

本题需要改变的是列数,也就是说,每行的元素个数可以不同,把这些元素个数存储在数组 row_size 中。其余不需要改变。

代码:

 1 #include <iostream>
 2 using namespace std;
 3 
 4 template <typename T>
 5 void make_2d_array (T** &x, int row_number, const int* row_size) {
 6     x = new T* [row_number];
 7 
 8     for (int i = 0; i < row_number; ++i) {
 9         x[i] = new T [row_size[i]];
10     }
11 }
12 
13 int main() {
14     int** x;
15     cout << "Enter row : ";
16     int row_number;
17     cin >> row_number;
18     int row_size[row_number];
19 
20     for (int i = 0; i < row_number; ++i) {
21         cout << "Enter row " << i << " size : ";
22         cin >> row_size[i];
23     }
24 
25     make_2d_array(x, row_number, row_size);
26 
27     for (int i = 0; i < row_number; ++i) {
28         for (int j = 0; j < row_size[i]; ++j) {
29             cout << "Enter [" << i << "][" << j << "] : ";
30             cin >> x[i][j];
31         }
32     }
33 
34     for (int i = 0; i < row_number; ++i) {
35         for (int j = 0; j < row_size[i]; ++j) {
36             cout << x[i][j] << " ";
37         }
38         cout << endl;
39     }
40 
41     return 0;
42 }

 

posted @ 2020-02-15 16:20  Hello_Nolan  阅读(260)  评论(0编辑  收藏  举报