2015-12-14 96 views
0

我得到了這個硬件問題,我真的堅持下去。我需要從文件加載這個矩陣。從文件加載矩陣

class matrix 
{ 
public: 
    matrix(matrix& other); //copy constructor 

    ~matrix(); //destructor 

    void LoadMatrix(string filename); 

    //load data from file into m 

    bool operator==(matrix& other); //compare two matrix 

private: 
    int** m; //2D dynamic array of integers 

    int height; //height of m 

    int width; //width of m 
}; 

從數據文件中的LoadMatrix功能加載數據,數據文件包含類似的數據:

2 3 
1 2 3 
3 4 8 

這是我到目前爲止有:

class matrix 
{ 
public: 
    matrix(matrix& other); //copy constructor 

    ~matrix(); //destructor 

    void LoadMatrix(string filename); 

    //load data from file into m 

    bool operator==(matrix& other); //compare two matrix 

private: 
    int** m; //2D dynamic array of integers 

    int height; //height of m 

    int width; //width of m 
}; 

matrix::matrix() 
{ 
} 

matrix::~matrix() 
{ 
    for (int i = 0; i < height; i++) 
    { 
     delete m[i]; 
    } 
    delete m; 
} 

void matrix::LoadMatrix(string filename) 
{ 
    ifstream infile(filename); 
    if (infile.is_open()) 
    { 
     string line1 = "", line2 = ""; 
     infile >> height; 
     infile >> width; 
     infile.ignore(); 
     m = new int*[height]; 
     for (int i = 0; i < height; i++) 
     { 
      m[i] = new int[width]; 
      line2 = ""; 
      getline(infile, line1); 
     } 
    } 
} 

int main() 
{ 
} 

任何提示將是巨大的, 謝謝!

+0

閱讀'n',讀取'm',讀取'm'整數的'n'行成一個數組。問題是什麼? –

+1

你爲什麼要這樣設計你的代碼? –

回答

1

這裏沒有真正的問題,除非它不起作用,它不編譯,爲什麼?

由於文件中矩陣的第一行似乎定義了矩陣的高度和寬度,並且考慮到只存儲整數,所以您只需執行一個雙重for-loop來將值存儲在每行中。

大概是這樣的:

void LoadFromFile(const std::string& iFile) 
{ 
    std::ifstream infile(iFile); 
    infile >> _height;  
    infile >> _width; 
    _m = new int*[_height]; 
    for (int i = 0; i < _height; ++i)  
    { 
     _m[i] = new int[_width];   
     for (int j = 0; j < _width; ++j)  
     { 
      infile >> _m[i][j]; 
     } 
    } 
} 

當然,你一定不相信在一個文件中提供的數據,這樣一些檢查在前面的代碼以復加。