1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
| #include <iostream>
#include <sstream>
#include <typeinfo>
#include <vector>
template<class T>
class Matrix
{
public:
Matrix(size_t rowCount, size_t colCount);
Matrix(Matrix<T>&&) = default;
Matrix(const Matrix<T>&) = default;
~Matrix() = default;
Matrix<T>& operator=(Matrix<T>&&) = default;
Matrix<T>& operator=(Matrix<T> other) {*this = std::move(other); return *this;}
size_t rowCount() const {return m_rowCount;}
size_t colCount() const {return m_colCount;}
T& operator()(size_t row, size_t col); //!< \warning pas de contrôle des indices
const T& operator()(size_t row, size_t col) const; //!< \warning pas de contrôle des indices
T& at (size_t row, size_t col); //!< \exception std::out_of_range indices incorrects
const T& at (size_t row, size_t col) const; //!< \exception std::out_of_range indices incorrects
private:
size_t m_rowCount;
size_t m_colCount;
std::vector<T> m_data;
};
template<class T>
Matrix<T>::Matrix(size_t rowCount, size_t colCount) :
m_rowCount(rowCount),
m_colCount(colCount),
m_data(rowCount*colCount)
{
}
template<class T>
const T& Matrix<T>::operator()(size_t row, size_t col) const
{
return m_data[col*m_rowCount + row]; // stockage colonne par colonne
// return m_data[row*m_colCount + col]; // stockage ligne par ligne
}
template<class T>
T& Matrix<T>::operator()(size_t row, size_t col)
{
return const_cast<T&>(static_cast<const Matrix<T>&>(*this)(row, col));
}
template<class T>
const T& Matrix<T>::at(size_t row, size_t col) const
{
if(row >= m_rowCount || col >= m_colCount) {
std::ostringstream oss;
oss << "Error: Matrix<T>::at [T = " << typeid(T).name() << "]:";
if(row >= m_rowCount)
oss << " Row index (" << row << ") out of range (number of rows: " << m_rowCount << ").";
if(col >= m_colCount)
oss << " Column index (" << col << ") out of range (number of columns: " << m_colCount << ").";
throw std::out_of_range(oss.str());
}
return (*this)(row, col);
}
template<class T>
T& Matrix<T>::at(size_t row, size_t col)
{
return const_cast<T&>(static_cast<const Matrix<T>&>(*this).at(row, col));
}
// Utilisation :
int main(int argc, char **argv)
{
// Construire une matrice :
Matrix<double> mat(3, 5);
for(size_t i = 0; i < mat.rowCount(); ++i)
for(size_t j = 0; j < mat.colCount(); ++j)
mat(i, j) = i+j;
// Afficher la matrice (code bourrin) :
for(size_t i = 0; i < mat.rowCount(); ++i) {
for(size_t j = 0; j < mat.colCount(); ++j)
std::cout << mat(i, j) << " ; ";
std::cout << '\n';
}
} |
Partager