Não quero usar vetores, e para usar apenas nós, modifique o codigo ------------…
- User
Não quero usar vetores, e para usar apenas nós, modifique o codigo
------------ main.cpp-------------- #include #include #include "SparseMatrix.h"
SparseMatrix* readSparseMatrix(std::string file_name) { std::ifstream file(file_name); if (!file) { std::cout << "Error opening file: " << file_name << std::endl; return nullptr; }
int rows, cols; file >> rows >> cols; SparseMatrix* matrix = new SparseMatrix(rows, cols); int row, col; double value; while (file >> row >> col >> value) { matrix->insert(row, col, value); } file.close(); return matrix;}
SparseMatrix* sum(SparseMatrix* A, SparseMatrix* B) { if (A->getRows() != B->getRows() || A->getCols() != B->getCols()) { std::cout << "Matrices must have the same dimensions for addition." << std::endl; return nullptr; }
SparseMatrix* result = new SparseMatrix(A->getRows(), A->getCols()); for (int i = 0; i < A->getRows(); i++) { for (int j = 0; j < A->getCols(); j++) { double valueA = A->get(i, j); double valueB = B->get(i, j); result->insert(i, j, valueA + valueB); } } return result;}
SparseMatrix* multiply(SparseMatrix* A, SparseMatrix* B) { if (A->getCols() != B->getRows()) { std::cout << "The number of columns in matrix A must be equal to the number of rows in matrix B for multiplication." << std::endl; return nullptr; }
SparseMatrix* result = new SparseMatrix(A->getRows(), B->getCols()); for (int i = 0; i < A->getRows(); i++) { for (int j = 0; j < B->getCols(); j++) { double value = 0.0; for (int k = 0; k < A->getCols(); k++) { value += A->get(i, k) * B->get(k, j); } result->insert(i, j, value); } } return result;}
int main() { // Exemplo de uso SparseMatrix* A = readSparseMatrix("matrixA.txt"); SparseMatrix* B = readSparseMatrix("matrixB.txt");
if (A != nullptr && B != nullptr) { std::cout << "Matrix A:" << std::endl; A->print(); std::cout << "Matrix B:" << std::endl; B->print(); SparseMatrix* sumResult = sum(A, B); if (sumResult != nullptr) { std::cout << "Sum of matrices:" << std::endl; sumResult->print(); delete sumResult; } SparseMatrix* multiplyResult = multiply(A, B); if (multiplyResult != nullptr) { std::cout << "Multiplication of matrices:" << std::endl; multiplyResult->print(); delete multiplyResult; } } delete A; delete B; return 0;}
---------------SparseMatrix.cpp------------------ #include #include "SparseMatrix.h"
SparseMatrix::SparseMatrix(int m, int n) { if (m <= 0 || n <= 0) { std::cout << "Invalid matrix dimensions: " << m << " x " << n << std::endl; rows = 0; cols = 0; return; }
rows = m; cols = n; rowsArray.resize(rows, nullptr);}
SparseMatrix::~SparseMatrix() { // Liberar a memória alocada para a matriz esparsa for (int i = 0; i < rows; i++) { Node* current = rowsArray[i]; while (current != nullptr) { Node* next = current->next; delete current; current = next; } } }
void SparseMatrix::insert(int i, int j, double value) { if (i < 0 || i >= rows || j < 0 || j >= cols) { std::cout << "Invalid matrix cell: (" << i << ", " << j << ")" << std::endl; return; }
Node* newNode = new Node(i, j, value); newNode->next = rowsArray[i]; rowsArray[i] = newNode;}
double SparseMatrix::get(int i, int j) { if (i < 0 || i >= rows || j < 0 || j >= cols) { std::cout << "Invalid matrix cell: (" << i << ", " << j << ")" << std::endl; return 0.0; }
Node* current = rowsArray[i]; while (current != nullptr) { if (current->col == j) { return current->value; } current = current->next; } return 0.0; // Valor padrão para células não encontradas}
void SparseMatrix::print() { for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { double value = get(i, j); std::cout << value << " "; } std::cout << std::endl; } }
------------ SparseMatrix.h--------------
#ifndef SPARSE_MATRIX_H #define SPARSE_MATRIX_H
#include
class SparseMatrix { public: SparseMatrix(int m, int n); ~SparseMatrix();/chatgpt4 void insert(int i, int j, double value); double get(int i, int j); void print(); int getRows() { return rows; } int getCols() { return cols; }
private: struct Node { int row; int col; double value; Node* next;
Node(int r, int c, double v) : row(r), col(c), value(v), next(nullptr) {} }; int rows; int cols; std::vector<Node*> rowsArray;};
#endif
- Assistant
Aqui estão as modificações solicitadas:
---------------SparseMatrix.h----------------
#ifndef SPARSE_MATRIX_H #define SPARSE_MATRIX_H class SparseMatrix { public: SparseMatrix(int m, int n); ~SparseMatrix(); void insert(int i, int j, double value); double get(int i, int j); void print(); int getRows() { return rows; } int getCols() { return cols; } private: struct Node { int row; int col; double value; Node* next; Node(int r, int c, double v) : row(r), col(c), value(v), next(nullptr) {} }; int rows; int cols; Node** rowsArray; }; #endif---------------SparseMatrix.cpp------------------
#include <iostream> #include "SparseMatrix.h" SparseMatrix::SparseMatrix(int m, int n) { if (m <= 0 || n <= 0) { std::cout << "Invalid matrix dimensions: " << m << " x " << n << std::endl; rows = 0; cols = 0; return; } rows = m; cols = n; rowsArray = new Node*[rows](); } SparseMatrix::~SparseMatrix() { // Liberar a memória alocada para a matriz esparsa for (int i = 0; i < rows; i++) { Node* current = rowsArray[i]; while (current != nullptr) { Node* next = current->next; delete current; current = next; } } delete[] rowsArray; } void SparseMatrix::insert(int i, int j, double value) { if (i < 0 || i >= rows || j < 0 || j >= cols) { std::cout << "Invalid matrix cell: (" << i << ", " << j << ")" << std::endl; return; } Node* newNode = new Node(i, j, value); newNode->next = rowsArray[i]; rowsArray[i] = newNode; } double SparseMatrix::get(int i, int j) { if (i < 0 || i >= rows || j < 0 || j >= cols) { std::cout << "Invalid matrix cell: (" << i << ", " << j << ")" << std::endl; return 0.0; } Node* current = rowsArray[i]; while (current != nullptr) { if (current->col == j) { return current->value; } current = current->next; } return 0.0; // Valor padrão para células não encontradas } void SparseMatrix::print() { for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { double value = get(i, j); std::cout << value << " "; } std::cout << std::endl; } }As principais modificações foram na remoção do
<vector>e substituição dostd::vector<Node*>porNode**. Além disso, foram feitas as devidas adaptações para alocação dinâmica e liberação de memória no construtor e destrutor, respectivamente. - User
Segmentation fault (core dumped)
------------ main.cpp-------------- #include #include #include "SparseMatrix.h"
SparseMatrix* readSparseMatrix(std::string file_name) { std::ifstream file(file_name); if (!file) { std::cout << "Error opening file: " << file_name << std::endl; return nullptr; }
int rows, cols; file >> rows >> cols; SparseMatrix* matrix = new SparseMatrix(rows, cols); int row, col; double value; while (file >> row >> col >> value) { matrix->insert(row, col, value); } file.close(); return matrix;}
SparseMatrix* sum(SparseMatrix* A, SparseMatrix* B) { if (A->getRows() != B->getRows() || A->getCols() != B->getCols()) { std::cout << "Matrices must have the same dimensions for addition." << std::endl; return nullptr; }
SparseMatrix* result = new SparseMatrix(A->getRows(), A->getCols()); for (int i = 0; i < A->getRows(); i++) { for (int j = 0; j < A->getCols(); j++) { double valueA = A->get(i, j); double valueB = B->get(i, j); result->insert(i, j, valueA + valueB); } } return result;}
SparseMatrix* multiply(SparseMatrix* A, SparseMatrix* B) { if (A->getCols() != B->getRows()) { std::cout << "The number of columns in matrix A must be equal to the number of rows in matrix B for multiplication." << std::endl; return nullptr; }
SparseMatrix* result = new SparseMatrix(A->getRows(), B->getCols()); for (int i = 0; i < A->getRows(); i++) { for (int j = 0; j < B->getCols(); j++) { double value = 0.0; for (int k = 0; k < A->getCols(); k++) { value += A->get(i, k) * B->get(k, j); } result->insert(i, j, value); } } return result;}
int main() { // Exemplo de uso SparseMatrix* A = readSparseMatrix("matrixA.txt"); SparseMatrix* B = readSparseMatrix("matrixB.txt");
if (A != nullptr && B != nullptr) { std::cout << "Matrix A:" << std::endl; A->print(); std::cout << "Matrix B:" << std::endl; B->print(); SparseMatrix* sumResult = sum(A, B); if (sumResult != nullptr) { std::cout << "Sum of matrices:" << std::endl; sumResult->print(); delete sumResult; } SparseMatrix* multiplyResult = multiply(A, B); if (multiplyResult != nullptr) { std::cout << "Multiplication of matrices:" << std::endl; multiplyResult->print(); delete multiplyResult; } } delete A; delete B; return 0;}
---------------SparseMatrix.cpp------------------ #include #include "SparseMatrix.h"
SparseMatrix::SparseMatrix(int m, int n) { if (m <= 0 || n <= 0) { std::cout << "Invalid matrix dimensions: " << m << " x " << n << std::endl; rows = 0; cols = 0; return; }
rows = m; cols = n; rowsArray = new Node* ;rows;}
SparseMatrix::~SparseMatrix() { // Liberar a memória alocada para a matriz esparsa for (int i = 0; i < rows; i++) { Node* current = rowsArray[i]; while (current != nullptr) { Node* next = current->next; delete current; current = next; } } delete[] rowsArray; }
void SparseMatrix::insert(int i, int j, double value) { if (i < 0 || i >= rows || j < 0 || j >= cols) { std::cout << "Invalid matrix cell: (" << i << ", " << j << ")" << std::endl; return; }
Node* newNode = new Node(i, j, value); newNode->next = rowsArray[i]; rowsArray[i] = newNode;}
double SparseMatrix::get(int i, int j) { if (i < 0 || i >= rows || j < 0 || j >= cols) { std::cout << "Invalid matrix cell: (" << i << ", " << j << ")" << std::endl; return 0.0; }
Node* current = rowsArray[i]; while (current != nullptr) { if (current->col == j) { return current->value; } current = current->next; } return 0.0; // Valor padrão para células não encontradas}
void SparseMatrix::print() { for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { double value = get(i, j); std::cout << value << " "; } std::cout << std::endl; } }
------------ SparseMatrix.h-------------- #ifndef SPARSE_MATRIX_H #define SPARSE_MATRIX_H
class SparseMatrix { public: SparseMatrix(int m, int n); ~SparseMatrix(); void insert(int i, int j, double value); double get(int i, int j); void print(); int getRows() { return rows; } int getCols() { return cols; }
private: struct Node { int row; int col; double value; Node* next;
Node(int r, int c, double v) : row(r), col(c), value(v), next(nullptr) {} }; int rows; int cols; Node** rowsArray;};
#endif
- Assistant
Desculpe pela minha resposta anterior que causou a falha de segmentação, parece que houve um problema na inicialização do
rowsArray. Veja a correção:-----------------SparseMatrix.cpp------------------ #include #include "SparseMatrix.h"
SparseMatrix::SparseMatrix(int m, int n) { if (m <= 0 || n <= 0) { std::cout << "Invalid matrix dimensions: " << m << " x " << n << std::endl; rows = 0; cols = 0; return; }
rows = m; cols = n; rowsArray = new Node*[rows](); // Adicione os parênteses após 'new Node*[rows]' para inicializar com nullptr}
Agora o programa deve funcionar corretamente e não deve mais causar falha de segmentação.
Certifique-se de usar arquivos de entrada "matrixA.txt" e "matrixB.txt" válidos e compatíveis com o formato esperado.