#include #include using namespace std; //using Matrix = vector< vector >; using Row = vector; // One row of the matrix using Matrix = vector; // Matrix: a vector of rows Matrix multiply(const Matrix& A, const Matrix& B); Matrix matrix_sumrow(const Matrix& A, const Matrix& B); Matrix matrix_sumcol(const Matrix& A, const Matrix& B); bool is_symmetric(const Matrix& A); void Transpose(Matrix& A); Matrix Read(); void Write(Matrix& A); // Dynamically Allocate Memory for 2D Array in C++ int main() { // Declaration of a matrix with 3 rows and 4 columns //vector< vector > my_matrix(3, vector(4)); Matrix A, B, C; A = Read(); B = Read(); C = matrix_sumrow(A,B); Write(A); Write(B); Write(C); Transpose(A); Write(A); } // Pre: A and B are non-empty matrices with the same size // Returns A+B (sum of matrices) Matrix matrix_sumrow(const Matrix& A, const Matrix& B) { int nrows = A.size(); int ncols = A[0].size(); Matrix C(nrows, vector(ncols)); for (int i = 0; i < nrows; ++i) { for (int j = 0; j < ncols; ++j) { C[i][j] = A[i][j] + B[i][j]; } } return C; } // Pre: A and B are non-empty matrices with the same size // Returns A+B (sum of matrices) Matrix matrix_sumcol(const Matrix& A, const Matrix& B) { int nrows = A.size(); int ncols = A[0].size(); Matrix C(nrows, vector(ncols)); for (int j = 0; j < ncols; ++j) { for (int i = 0; i < nrows; ++i) { C[i][j] = A[i][j] + B[i][j]; } } return C; } // Pre: A is a non-empty n×m matrix, B is a non-empty m×p matrix // Returns A×B (an n×p matrix) Matrix multiply(const Matrix& A, const Matrix& B) { int n = A.size(); int m = A[0].size(); int p = B[0].size(); Matrix C(n, vector(p)); for (int i = 0; i < n; ++i) { for (int j = 0; j < p; ++j) { int sum = 0; for (int k = 0; k < m; ++k) { sum += A[i][k]*B[k][j]; } C[i][j] = sum; } } return C; } // Pre: A is a square matrix // Returns true if A is symmetric, and false otherwise bool is_symmetric(const Matrix& A) { int n = A.size(); for (int i = 0; i < n - 1; ++i) { for (int j = i + 1; j < n; ++j) { if (A[i][j] != A[j][i]) return false; } } return true; } // Pre: A is a square matrix // Post: A contains the transpose of the input matrix void Transpose(Matrix& A) { int n = A.size(); for (int i = 1; i < n; ++i) { for (int j = 0; j < i; ++j) { swap(A[i][j], A[j][i]); } } } Matrix Read() { int nf,nc; cout << "Ingresa numero de filas y columnas: "; cin >> nf >> nc; // elegant declaration using Row = vector; // One row of the matrix using Matrix = vector; // Matrix: a vector of rows Matrix A(nf, Row(nc)); // The same matrix as above for (int i = 0; i < nf; ++i) { for (int j = 0; j < nc; ++j) { cout << "Ingresa elemento " << i << "," << j << ": "; cin >> A[i][j]; } } return A; } void Write(Matrix& A) { int nrows = A.size(); int ncols = A[0].size(); for (int i = 0; i < nrows; ++i) { for (int j = 0; j < ncols; ++j) { cout << A[i][j] << " "; } cout << endl; } }