CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2

Threaded View

  1. #1
    Join Date
    May 2000
    Location
    KY, USA
    Posts
    18,652

    C++ General: How to declare and use two-dimensional arrays?

    Q: How can I define a dynamic two-dimensional array?

    A: The following class shows one way of encapsulating a two-dimensional array:

    Code:
    template <class T>
    class dynamic_2d_array
    {
    public:
      dynamic_2d_array(int row, int col) : m_row(row),
                                           m_col(col),
                                           m_data((row != 0 && col != 0) ? new T[row * col] : NULL){}
    
      dynamic_2d_array(const dynamic_2d_array& src) : m_row(src.m_row),
                                                      m_col(src.m_col),
                                                      m_data((src.m_row != 0 && src.m_col != 0) ? new T[src.m_row * src.m_col] : NULL)
      {
        for(int r = 0;r < m_row; ++r)
          for(int c = 0; c < m_col; ++c)
            (*this)[r][c] = src[r][c];
      }
    
      ~dynamic_2d_array()
      {
        if(m_data)
          delete []m_data;
      }
      
      inline T* operator[](int i) { return (m_data + (m_col * i)); }
    
      inline T const*const operator[](int i) const {return (m_data + (m_col * i)); }
    
    
    private:
      dynamic_2d_array& operator=(const dynamic_2d_array&);
      const int m_row;
      const int m_col;
      T* m_data; 
    };
    A different approach using the STL 'vector' class is shown in the following FAQ...


    FAQ contributed by: [Axter]


    Last edited by Andreas Masur; July 23rd, 2005 at 12:36 PM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured