2017-09-26 215 views
0

我正在C++中製作一個模板化的矩陣類。爲了創建這個類,我創建了一個指針數組,這些指針指向動態數組。C++模板類指向數組的指針動態數組

到目前爲止,我有:

template<typename T> class Matrix 
    { 
    public: 
     //constructor 
     int **m = new int*[_rows]; 
     for (int i = 0; i < _rows; i++) 
     { 
      m[i] = new int[_cols]; 
     } 

     //destructor 
     for (int i = 0; i < _rows; i++) 
     { 
      delete[] m[i] 
     } 
     delete[] m; 
    }; 

我也想創造一些函數來處理這樣的結構。 我看過很多類似這樣的代碼,但我沒有看到這是如何創建一個包含指向其他數組的指針的數組。這個概念讓我感到困惑,我只希望有人向我澄清我應該怎樣做我想做的事情。

我想讓這個類被隔離,而且與輸入無關。它可能會在其他代碼中被調用並使用我的函數來創建矩陣結構。創建指針數組並不是我感到困惑的部分,它使這些指針指向其他數組,指針數組的大小根據其中有多少個輸入條目而增加。

+1

讓您的生活更輕鬆,只需使用'std :: vector'而不是指針和原始內存管理。 – PaulMcKenzie

+0

謝謝。從概念上講,我正在嘗試使用動態分配的數組來實現嗎? – AustinGlad

+0

當然這是可能的。矢量如何在內部工作?它與你想要做的沒有什麼不同,只是更安全。其次,你的目標是開發一個Matrix類或者動態數組管理嗎?如果要開發Matrix類,那麼使用'vector'就可以開始開發Matrix類的實際工作。 – PaulMcKenzie

回答

0
#include <iostream> 

using namespace std; 

template<typename T> class Matrix 
{ 
public: 
    Matrix(int row, int col) 
    { 
     _rows = row; 
     _cols = col; 
     m = new T*[_rows]; 
     for (int i = 0; i < _rows; i++) 
     { 
      m[i] = new T[_cols]; 
      for(int j=0; j < _cols; j++) 
      { 
       m[i][j] = i*10 + j; 
      } 
     } 
    } 

    ~Matrix() 
    { 
     for (int i = 0; i < _rows; i++) 
     { 
      delete[] m[i]; 
     } 
     delete[] m; 
    } 

    T **m; 
    int _rows; 
    int _cols; 
}; 

void main() 
{ 
    Matrix<int> a(3,4); 

    for(int i=0; i<a._rows; i++) 
    { 
     for(int j=0; j<a._cols; j++) 
     { 
      cout << "[" << i << "][" << j << "]" << a.m[i][j] << " "; 
     } 
     cout << endl; 
    } 

} 

結果:

[0] [0] 0 [0] [1] 1 [0] [2] 2 [0] [3] 3

[1] [0 ] 10 [1] [1] 11 [1] [2] 12 [1] [3] 13

[2] [0] 20 [2] [1] 21 [2] [2] 22 [2 ] [3] 23