矩阵 - 从文件中读取

时间:2015-01-22 16:37:11

标签: c++ memory matrix

我在使用函数从文件中读取矩阵时遇到了问题...

我的班级看起来像这样:

 #include<iostream>
#include<cmath>
#include<string>
#include<fstream>

using namespace std;

class Matrix
{   
public:
Matrix(int, int);
Matrix(const Matrix& copyMatrix);
~Matrix();
Matrix(const char *sciezka);
Matrix& wypelnij(string);
friend ostream& operator<< (ostream&, Matrix&);
Matrix& operator+= (const Matrix&);  
Matrix& operator-= (const Matrix&);
Matrix& operator*= (const Matrix&);
Matrix& operator= (const Matrix&); 
friend Matrix operator* (const Matrix & left, const Matrix & right); 
friend Matrix operator+ (const Matrix & left, const Matrix & right); 
friend Matrix operator- (const Matrix & left, const Matrix & right); 
class AllocError{}; 
class OpenError{}; 
class IncorrectSize{}; 
private:
double **macierz;
unsigned int wiersze, kolumny;      
};

构造

Matrix::Matrix(int x = 1, int y = 1): wiersze(x), kolumny(y)
{

if (wiersze < 1 || kolumny < 1) 
{
    throw AllocError();
}
macierz = new double*[wiersze];

for (unsigned i = 0; i < wiersze; i++)
{
    macierz[i] = new double[kolumny];
    for (unsigned j = 0; j < kolumny; j++)
    {
        macierz[i][j] = 0;
    }
}
}

Matrix::Matrix(const Matrix& copyMatrix)
{
wiersze=copyMatrix.wiersze;
kolumny=copyMatrix.kolumny;

macierz = new double*[wiersze];

for (unsigned i = 0; i < wiersze; i++)
{
    macierz[i] = new double[kolumny];
    for (unsigned j = 0; j < kolumny; j++)
    {
        macierz[i][j] = copyMatrix.macierz[i][j];
    }
}   
}

最后是函数

Matrix::Matrix(const char *sciezka)
{
ifstream plik(sciezka);
if (plik.good() != true) 
{
    throw OpenError();
}
unsigned w, k;
plik >> w >> k;
if (w < 1 || k < 1) throw AllocError();
double **temp = new double*[w];
double *pamiec = new double[w * k];

    for (unsigned i = 0; i < w; i++)
{
    temp[i] = pamiec + (i * k);
}
for (unsigned i = 0; i < w; i++)
{
    for (unsigned j = 0; j < k; j++)
    {
        plik >> temp[i][j];
    }   
}   
wiersze=w;
kolumny=k;
macierz=temp;

//for (unsigned i = 0; i < w; i++)       //IT WORKS TOO
//      {
//          macierz[i] = temp[i];
//  }
for (unsigned i = 0; i < w; i++)
{
    for (unsigned j = 0; j < k; j++)
    {
        macierz[i][j] = temp[i][j];
    }   
}

plik.close();
//delete [] *temp;
 //delete [] temp;  
}

当我在功能结束时不使用删除时,它工作得很好,当我这样做时,有些数字是错误的。如果我在完成所有计算之后没有崩溃Matrix A(&#34; text.txt&#34;)Matrix B(5,5)Fill.B(&#34; B&#34;)Matrix C(5,5) C = A + B等...

@edit

我刚刚将F的结尾改为:

wiersze=w;
kolumny=k;
//macierz=temp;

macierz = new double*[w];
for (unsigned i = 0; i < w; i++)
{
    macierz[i] = new double[k];
    for (unsigned j = 0; j < k; j++)
    {
        macierz[i][j] = temp[i][j];
    }   
}

 plik.close();
delete [] *temp;
delete [] temp; 
}

有没有更简单的方法从文件中读取?我真的不喜欢这段代码

1 个答案:

答案 0 :(得分:0)

要删除矩阵,您应遵循相反的分配顺序,以下应该:

for (unsigned i = 0; i < w; i++)
{
    delete [] macierz[i] ;
}
delete [] macierz ;