From c2fd2805fac5c777b1d2e53b19f22519fafc6313 Mon Sep 17 00:00:00 2001 From: Persson-dev Date: Fri, 16 Feb 2024 10:02:27 +0100 Subject: [PATCH] matrix stream operators --- src/Matrix.cpp | 40 +++++++++++++++++++++++++--------------- src/Matrix.h | 3 +++ 2 files changed, 28 insertions(+), 15 deletions(-) diff --git a/src/Matrix.cpp b/src/Matrix.cpp index 465bc55..a64fb97 100644 --- a/src/Matrix.cpp +++ b/src/Matrix.cpp @@ -74,13 +74,7 @@ void Matrix::Save(const std::string& fileName) { std::cerr << "Impossible de sauvegarder la matrice !\n"; return; } - out << m_Lignes << " " << m_Colonnes << "\n"; - for (std::size_t i = 0; i < m_Lignes; i++) { - for (std::size_t j = 0; j < m_Colonnes; j++) { - out << at(i, j) << " "; - } - out << "\n"; - } + out << *this; } void Matrix::Load(const std::string& filename) { @@ -89,13 +83,7 @@ void Matrix::Load(const std::string& filename) { std::cerr << "Impossible de charger la matrice !\n"; return; } - in >> m_Lignes >> m_Colonnes; - m_Data.resize(m_Lignes * m_Colonnes); - for (std::size_t i = 0; i < m_Lignes; i++) { - for (std::size_t j = 0; j < m_Colonnes; j++) { - in >> at(i, j); - } - } + in >> *this; } void Matrix::Transpose() { @@ -266,4 +254,26 @@ Matrix Matrix::SubMatrix(std::size_t origine_ligne, std::size_t origine_colonne, } return result; -} \ No newline at end of file +} + +std::ostream& operator<<(std::ostream& stream, const Matrix& mat) { + stream << mat.m_Lignes << " " << mat.m_Colonnes << "\n"; + for (std::size_t i = 0; i < mat.m_Lignes; i++) { + for (std::size_t j = 0; j < mat.m_Colonnes; j++) { + stream << mat.at(i, j) << " "; + } + stream << "\n"; + } + return stream; +} + +std::istream& operator>>(std::istream& stream, Matrix& mat) { + stream >> mat.m_Lignes >> mat.m_Colonnes; + mat.m_Data.resize(mat.m_Lignes * mat.m_Colonnes); + for (std::size_t i = 0; i < mat.m_Lignes; i++) { + for (std::size_t j = 0; j < mat.m_Colonnes; j++) { + stream >> mat.at(i, j); + } + } + return stream; +} diff --git a/src/Matrix.h b/src/Matrix.h index a858f89..4e61977 100644 --- a/src/Matrix.h +++ b/src/Matrix.h @@ -55,6 +55,9 @@ class Matrix { long double& at(std::size_t ligne, std::size_t colonne); long double at(std::size_t ligne, std::size_t colonne) const; + + friend std::ostream& operator<<(std::ostream& stream, const Matrix& mat); + friend std::istream& operator>>(std::istream& stream, Matrix& mat); }; template