Краткое описание проблемы
Без использования векторного класса или любого другого класса STL мне нужно создать динамическую матрицу. Центральная ось проблемы заключается в том, что «основной файл» будет запускать эту программу, вызывая конструктор текстовых файлов (позже я объясню) с некоторыми координатами, и мне нужно будет поставить 1 в этих координатах и динамически увеличивать матрицу.
Вот пример текстового файла:
example.txt
0 1 // 0 is the row and 1 the column, therefore in the position of the matrix (0,1) should be a 1.
0 2 // (0,2) = 1
1 4 // (1,4) = 1
1 6 // (1,6) = 1
9 9 // (9,9) = 1
Все остальные координаты должны быть равны 0.
Основное будет выглядеть так:
...
SparseMatrix m1("example.txt");
...
Это проблема плохого распределения , если я запускаю программу без какого-либо освобождения, она работает нормально!
ВВ следующем разделе я объясню каждый метод класса SparseMatrix, который мне нужно создать.
class SparseMatrix
{
public:
SparseMatrix();
SparseMatrix(int rows, int cols);
SparseMatrix(const SparseMatrix& m);
SparseMatrix(const string& filename);
~SparseMatrix();
SparseMatrix& operator=(const SparseMatrix& m);
void init(int rows, int cols);
int getrows() const { return m_rows; }
int getcols() const { return m_cols; }
bool getVal(int row, int col, float& value);
void setVal(int row, int col, float value);
private:
float** m_matrix;
int m_rows;
int m_cols;
};
Конструктор по умолчанию: SparseMatrix ()
SparseMatrix()
{
m_rows = 0;
m_cols = 0;
m_matrix = nullptr;
}
Конструктор с параметрами: SparseMatrix (int row, int cols)
Создание матрицы с учетом ее строк и столбцов и ее инициализация равной 0.
SparseMatrix(int rows, int cols)
{
m_rows = rows;
m_cols = cols;
m_matrix = new float* [m_rows];
for (int i = 0; i <= m_rows; i++)
{
m_matrix[i] = new float[m_cols];
}
for (int i = 0; i <= m_rows; i++)
{
for (int j = 0; j <= m_cols; j++)
{
m_matrix[i][j] = 0;
}
}
}
Copy Constructor: SparseMatrix (const SparseMatrix & m)
SparseMatrix(const SparseMatrix& m)
{
m_rows = m.m_rows;
m_cols = m.m_cols;
if (m.m_matrix != nullptr)
{
m_matrix = new float* [m_rows];
for (int i = 0; i <= m_rows; i++)
{
m_matrix[i] = new float[m_cols];
}
for (int i = 0; i <= m_rows; i++)
{
for (int j = 0; j <= m_cols; j++)
{
m_matrix[i][j] = m.m_matrix[i][j];
}
}
}
else
m_matrix = nullptr;
}
Конструктор текстовых файлов: SparseMatrix (const string & example.txt)
Вот что, вероятно, хуже. Сначала я читаю первые две координаты, инициализирую, создаю матрицу и присваиваю этим координатам значение 1.
После инициализации я посвящаю себя только вставке значений и, если необходимо, созданию матрицыбольше (это делается методом setVal).
SparseMatrix(const string& nomFitxer)
{
ifstream file;
int row;
int col;
file.open(nomFitxer);
if (file.is_open())
{
file >> row;
file >> col;
init(row, col);
setVal(row, col, 1);
while (!file.eof())
{
file >> row;
file >> col;
setVal(row, col, 1);
}
}
file.close();
}
Деструктор: ~ SparseMatrix ()
~SparseMatrix()
{
if (m_matrix != nullptr)
{
for (int i = 0; i <= m_rows; i++)
delete[] m_matrix[i];
delete[] m_matrix;
}
}
Оператор назначения: SparseMatrix & operator= (const Sparse Matrix & m)
SparseMatrix& operator=(const SparseMatrix& m)
{
if (this != &m)
{
m_rows = m.m_rows;
m_cols = m.m_cols;
if (m_matrix != nullptr) // Deallocate
{
for (int i = 0; i <= m_rows; i++)
delete[] m_matrix[i];
delete[] m_matrix;
}
if (m.m_matrix != nullptr)
{
m_matrix = new float* [m_rows];
for (int i = 0; i <= m_rows; i++)
{
m_matrix[i] = new float[m_cols];
}
for (int i = 0; i <= m_rows; i++)
{
for (int j = 0; j <= m_cols; j++)
{
m_matrix[i][j] = m.m_matrix[i][j];
}
}
}
else
m_matrix = nullptr;
}
return *this;
}
Метод инициализации: void Init (int row, int cols)
Я знаю, что созданиесоздание Матрицы должно быть задачей конструктора, но как я могу создать матрицу из «Конструктора текстовых файлов»?
void init(int rows, int cols)
{
m_rows = rows;
m_cols = cols;
m_matrix = new float* [m_rows];
for (int i = 0; i <= m_rows; i++)
{
m_matrix[i] = new float[m_cols];
}
for (int i = 0; i <= m_rows; i++)
{
for (int j = 0; j <= m_cols; j++)
{
m_matrix[i][j] = 0;
}
}
}
Получатель значения: bool getVal (int row, int col, float & value)
bool getVal(int row, int col, float& value)
{ // I have to return a boolean if the position exists and return the value by reference to a parameter.
bool trobat = false;
if (row <= m_rows && col <= m_cols)
{
value = m_matrix[row][col];
trobat = true;
return trobat;
}
else
return trobat;
}
Установка значения: void setVal (int, int, col, значение с плавающей запятой)
void setVal(int row, int col, float value)
{
if (value != 0)
{
if (row <= m_rows && col <= m_cols)
m_matrix[row][col] = value;
else
{
SparseMatrix s(m_rows, m_cols);
// In the following lines I choose the biggest value between rows and cols to make the square matrix with the right parameters.
if (row > m_rows)
s.m_rows = row;
if (col > m_cols)
s.m_cols = col;
if (s.m_rows < s.m_cols)
s.m_cols = s.m_rows;
else
s.m_rows = s.m_cols;
s.init(s.m_rows, s.m_cols);
for (int i = 0; i <= s.m_rows; i++) // We assign the values of the old matrix to the new one and insert the value to the coordenates we have to
{
for (int j = 0; j <= s.m_cols; j++)
{
if (i == row && j == col)
s.m_matrix[i][j] = value;
else if (i <= m_rows && j <= m_cols && m_matrix!=nullptr)
{
s.m_matrix[i][j] = m_matrix[i][j];
}
else
{
s.m_matrix[i][j] = 0;
}
}
}
*this = s; //The assignment operator will deallocate my "old" matrix.
}
}
}