- //程序运行时在内存堆中动态分配2维数组模板
- #include<iostream>
- using namespace std;
- template<class Type>
- void Make2DArray(Type** &x,int rows,int cols)
- {
- x = new Type*[rows]; //创建rows个行指针的指针数组
- for(int i = 0;i<cols;i++)
- { //每一行指向含cols个元素的Type数组
- x[i] = new int[cols];
- }
- }
- template<class Type>
- void Delete2DArray(Type** &x,int rows)
- {
- for(int i =0;i<rows;i++)
- { //释放每一行
- delete []x[i];
- }
- delete []x; //释放行指针
- x = NULL; //设为0 防止用户继续访问
- }
- template<class Type>
- void Init2DArray(Type** &x,int rows,int cols)
- {//初始化
- for(int i=0;i<rows;i++)
- {
- for(int j =0;j<cols;j++)
- {
- cout<<"please input element["<<i<<"]["<<j<<"]:";
- cin>>x[i][j];
- }
- }
- }
- template<class Type>
- void Print2DArray(Type** x,int rows,int cols)
- {
- for(int i=0;i<rows;i++)
- {
- for(int j =0;j<cols;j++)
- {
- cout<<x[i][j]<<' ';
- }
- cout<<endl;
- }
- }
- int main()
- {
- int** array;
- int rows,cols;
- cin>>rows>>cols;
- Make2DArray<int>(array,rows,cols);
- Init2DArray<int>(array,rows,cols);
- Print2DArray<int>(array,rows,cols);
- Delete2DArray<int>(array,rows);
- return 0;
- }