C++中使用模板,new创建2维动态数组

 1 // 使用模板和new创建2维动态数组
 2 
 3 #include<iostream>
 4 #include<exception>
 5 #include<cstdlib>
 6 #include<iomanip>
 7 using namespace std;
 8 
 9 template<class Type>
10 bool Make2DArray(Type **&x,int rows,int cols)
11 {
12     int i;
13     try
14     {
15         // 创建行指针
16         x=new Type *[rows];
17         // 为每一行分配空间
18         for(i=0;i<rows;i++)
19         {
20             x[i]=new Type [cols];
21         }
22         return true;
23     }
24     catch(bad_alloc)
25     {
26         return false;
27     }
28     
29 }
30 
31 int main()
32 {
33     int **x,rows,cols,i,j;
34     bool flag;
35     cout<<"输入创建动态数组的行数rows= ";
36     cin>>rows;
37     cout<<"输入创建动态数组的列数cols= ";
38     cin>>cols;
39     flag=Make2DArray(x,rows,cols);
40     if(flag==true)
41     {
42         for(i=0;i<rows;i++)
43         {
44             for(j=0;j<cols;j++)
45             {
46                 x[i][j]=j+i*cols;
47             }
48         }
49     }
50     cout<<"输出创建的数组:
";
51     for(i=0;i<rows;i++)
52     {
53         for(j=0;j<cols;j++)
54         {
55             cout<<setw(3)<<x[i][j];
56         }
57         cout<<endl;
58     }
59     return 0;
60 }

调试运行结果:

原文地址:https://www.cnblogs.com/yuzhuwei/p/4173591.html