2维数组模板

Code:
  1. //程序运行时在内存堆中动态分配2维数组模板   
  2.   
  3. #include<iostream>   
  4. using namespace std;   
  5.   
  6.   
  7. template<class Type>   
  8. void Make2DArray(Type** &x,int rows,int cols)   
  9. {   
  10.     x = new Type*[rows];   //创建rows个行指针的指针数组   
  11.     for(int i = 0;i<cols;i++)   
  12.     {   //每一行指向含cols个元素的Type数组   
  13.         x[i] = new int[cols];    
  14.     }   
  15. }   
  16.   
  17. template<class Type>   
  18. void Delete2DArray(Type** &x,int rows)   
  19. {   
  20.     for(int i =0;i<rows;i++)   
  21.     {   //释放每一行   
  22.         delete []x[i];   
  23.     }   
  24.     delete []x;      //释放行指针   
  25.     x = NULL;       //设为0 防止用户继续访问   
  26. }   
  27.   
  28. template<class Type>   
  29. void Init2DArray(Type** &x,int rows,int cols)   
  30. {//初始化   
  31.     for(int i=0;i<rows;i++)   
  32.     {   
  33.         for(int j =0;j<cols;j++)   
  34.         {   
  35.             cout<<"please input element["<<i<<"]["<<j<<"]:";   
  36.             cin>>x[i][j];   
  37.         }   
  38.     }   
  39. }   
  40.   
  41. template<class Type>   
  42. void Print2DArray(Type** x,int rows,int cols)   
  43. {   
  44.     for(int i=0;i<rows;i++)   
  45.     {   
  46.         for(int j =0;j<cols;j++)   
  47.         {   
  48.             cout<<x[i][j]<<' ';   
  49.         }   
  50.         cout<<endl;   
  51.     }   
  52. }   
  53.   
  54. int main()   
  55. {   
  56.     int** array;   
  57.     int rows,cols;   
  58.     cin>>rows>>cols;   
  59.     Make2DArray<int>(array,rows,cols);   
  60.     Init2DArray<int>(array,rows,cols);   
  61.     Print2DArray<int>(array,rows,cols);   
  62.     Delete2DArray<int>(array,rows);   
  63.     return 0;   
  64. }   

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值