2014-09-19 26 views
0

我正在嘗試製作一個矩陣類,到目前爲止我已經創建了一個可以製作矢量矢量的成員,但我不確定如何去調整矢量大小如果需要的話。矩陣類和零參數問題

EX:resizeArray(3,3)應該返回一個3x3向量。

而且,由於某些原因,當我打電話給我的默認成員,矩陣(),我得到一個錯誤,指出... 「請求在myMatrix的,它的類型是矩陣[] []的成員numRows行」 我我不完全確定這是要求什麼,並且在其他地方找不到合適的答案。

在此先感謝

#include <iostream> 
#include <vector> 
using namespace std; 

template <typename Object> 
class matrix 
{ 
    public: 
    matrix() : array(1) 
    { 
      rows = 1; 
      cols = 1; 
     for(int i = 0; i < rows; i++) 
      array[ i ].resize(cols); 
    }  

    matrix(int rows, int cols) : array(rows) 
    { 
     for(int i = 0; i < rows; i++) 
      array[ i ].resize(cols); 
    } 

    const vector<Object> & operator[](int row) const 
    { 
     return array[ row ]; 
    } 

    vector<Object> & operator[](int row) 
    { 
     return array[ row ]; 
    } 

    int numrows() const 
    { 
     return array.size(); 
    } 

    int numcols() const 
    { 
     return numrows() ? array[ 0 ].size() : 0; 
    } 

    void resizeArray(int rows, int cols) 
    { 

     } 

    private: 
     vector< vector<Object> > array; 
     int rows; 
     int cols; 
}; 


int main() 
{ 
    matrix<int> myMatrix(3,2); 
    //matrix<int> myMatrix1(); 
    cout << myMatrix.numrows(); 
    cout << "\n"; 
    cout << myMatrix.numcols(); 
    system("PAUSE"); 
    return 0; 
} 
+0

你可以從我添加到http://stackoverflow.com/questions/17259877/1d-or-2d-array-whats-faster/17260533#17260533的例子。 (注意它是一個1d矩陣類,不過)。 – Pixelchemist 2014-09-19 22:43:00

+0

這是一個很好的鏈接,但最終我的問題是我不知道如何將我的矩陣傳遞給我的函數,然後調整它的大小。 我知道我應該能夠做到這一點類似於我如何創建對象,但我不能想出一個可行的解決方案。 – clf01 2014-09-19 23:02:50

回答

0

你可能想避免在矩陣類像載體的載體。它會導致非連續的內存分配,從而減慢執行速度。內部向量也會增加不必要的開銷。您可以考慮使用大小爲n*m的單個向量,其中nm分別是行數和列數。調整大小也更容易。

我正在使用gcc 4.8.1並且您的代碼有效。

0
#include <iostream> 
#include <vector> 
using namespace std; 

template <typename Object> 
class matrix 
{ 
public: 
    matrix() 
     : array(1) 
    { 
     rows = 1; 
     cols = 1; 
     for(int i = 0; i < rows; i++) 
      array[ i ].resize(cols); 
    }  

    matrix(int rows, int cols) // you forgot to assign the members rows and cols 
     : array(rows), rows(rows), cols(cols) 
    { 
     for(int i = 0; i < rows; i++) 
      array[ i ].resize(cols); 
    } 

    const vector<Object> & operator[](int row) const 
    { 
     return array[ row ]; 
    } 

    vector<Object> & operator[](int row) 
    { 
     return array[ row ]; 
    } 

    int numrows() const 
    { 
     return array.size(); 
    } 

    int numcols() const 
    { 
     return numrows() ? array[ 0 ].size() : 0; 
    } 

    void resizeArray(int rows, int cols) 
    { 
     this->rows = rows; 
     this->cols = cols; 
     array.resize(rows); 
     for(int i = 0; i < rows; i++) 
      array[i].resize(cols); 
    } 

private: 
    vector< vector<Object> > array; 
    int rows; 
    int cols; 
};