2017-05-30 176 views
0

我有一個矩陣類,我希望能夠用括號列表初始化二維數據數組的值。我發現我可以通過在調用構造函數之前聲明2D數組,然後將其作爲構造函數參數傳遞來實現此目的。但是,我希望能夠直接傳遞括號列表作爲參數。通過構造函數初始化類中的二維數組

template <class T, unsigned int N, unsigned int M> 
class Matrix 
{ 
    T data[N][M]; 

    Matrix(const T initMat[N][M]) 
    { 
     for (unsigned int i=0; i<N; ++i) 
     { 
      for (unsigned int j=0; j<M; ++j) 
      { 
       data[i][j] = initMat[i][j]; 
      } 
     } 
    } 
}; 




const double arr[2][2] = {{1.0,2.0},{3.0,4.0}}; 
Matrix<double, 2, 2> matA(arr); // Valid 


Matrix<double, 2, 2> matB({{1.0,2.0},{3.0,4.0}}); // Invalid 

有沒有辦法來實現這一目標?我試圖使用嵌套的std ::數組無效(大概是因爲它們的行爲與c樣式數組相同)。通過初始化列表可以實現這一點嗎? (我曾嘗試使用初始化列表,但我不確定它們是否不合適,或者它們的行爲不像我期望的那樣)。

我正在使用gcc和C++ 14。

回答

5

添加一個構造函數,如:

Matrix(std::array<std::array<T, M>, N> const& initMat) { ... } 

並添加另一組花括號中(對於std::array對象):

Matrix<double, 2, 2> matB({{{1.0,2.0},{3.0,4.0}}}); 

或者使用std::initialize_list,如:

Matrix(std::initializer_list<std::initializer_list<T>>){} 

然後y OU可以從上述定義丟棄圓括號(和一對大括號的):

Matrix<double, 2, 2> matB{{1.0,2.0},{3.0,4.0}}; 

與此缺點是初始化列表的尺寸將不被執行。因此我推薦使用std::array的第一個變體。

+2

你能解釋爲什麼我們必須使用這些額外的花括號嗎? –

+1

@AndreasH。他們是爲'std :: array'對象本身。 –

+0

* std :: array *的非常整潔的用法! –

相關問題