zoukankan      html  css  js  c++  java
  • 用模板实现动态数组

    http://topic.csdn.net/t/20040609/05/3075498.html

     
      申请与释放2至3维数组的函数  
      template<class   T>  
      inline   void   Intialize2DArray(T   **&xxx,   long   rows,   long   cols)  
      {  
      long   i,   j;  
      for   (i=0;   i<rows;   i++)  
      {  
      for   (j=0;   j<cols;   j++)  
      {  
      xxx[i][j]   =   T(0);  
      }  
      }  
      }  
       
      template<class   T>  
      void   Create2DArray(T   **&xxx,   long   rows,   long   cols)  
      {  
      xxx   =   new   T   *[rows];  
      for   (long   i=0;   i<rows;   i++)  
      {  
      xxx[i]=new   T[cols];  
      }  
      Intialize2DArray(xxx,   rows,   cols);  
      }  
       
      //删除2维数组时只需2个参数,不需要传数组的第2维大小  
      template<class   T>  
      void   Delete2DArray(T   **&xxx,   long   rows)  
      {  
      for(long   i=0;   i<rows;   i++)  
      {  
      delete   []xxx[i];  
      }  
      delete   []xxx;  
      xxx=0;  
      }  
       
      template<class   T>  
      void   Create3DArray(T   ***&xxx,   long   n1,   long   n2,   long   n3)  
      {  
      xxx   =   new   T   **[n1];  
      for   (long   i=0;   i<n1;   i++)  
      {  
      Create2DArray(xxx[i],   n2,   n3);  
      Intialize2DArray(xxx[i],   n2,   n3);  
      }  
      }  
       
      //删除3维数组时只需3个参数,不需要传数组的第3维大小  
      template<class   T>  
      void   Delete3DArray(T   ***&xxx,   long   n1,   long   n2)  
      {  
      for   (long   i=0;   i<n1;   i++)  
      {  
      Delete2DArray(xxx[i],   n2);  
      }  
      delete   []xxx;  
      xxx=0;  
      }  
       
      举例:使用3维数组  
         
                        int   n1   =   100;  
      int   n2   =   100;  
      int   n3   =   100;  
      float   ***array_3D;  
      Create3DArray(array_3D,   n1,   n2,   n3);  
       
      ...//use   the   3d   array   in   form   "array_3D[i][j][k]"  
       
      Delete3DArray(array_3D,   n1,   n2);
  • 相关阅读:
    转: CEF嵌入到单文档mfc
    浅谈C++多态性
    C++面试整理1
    面试汇总
    【转】一些经典的笔试题
    C# 委托
    搭建Nuget
    thinkphp框架之模型(数据库查询)
    利用csc.exe 手动编译C#程序
    css
  • 原文地址:https://www.cnblogs.com/cy163/p/607335.html
Copyright © 2011-2022 走看看