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
|
#include <iostream>
#include <vector>
#include <algorithm>
#include <iomanip>
class Matrix
{
public:
Matrix() = default ;
Matrix( std::size_t nrows, std::size_t ncols, double num = 0 )
: mtx( nrows, std::vector<double>( ncols, num ) ) {}
// note: type corrected to double
Matrix( std::initializer_list<std::initializer_list<double> > ilist ) : mtx( ilist.size() )
{
std::size_t col_size = 0 ; // size of the largest col
for( const auto& row : ilist ) col_size = std::max( col_size, row.size() ) ;
for( auto& row : mtx ) row.resize(col_size) ; // resize all columns to col_size
std::size_t row_num = 0 ;
for( const auto& row : ilist ) // copy what is there in each row of ilist
std::copy( row.begin(), row.end(), mtx[row_num++].begin() ) ;
}
// checked element access
double& element_at( std::size_t i, std::size_t j ) { return mtx.at(i).at(j) ; }
double element_at( std::size_t i, std::size_t j ) const { return mtx.at(i).at(j) ; }
// unchecked element access
double& operator() ( std::size_t i, std::size_t j ) { return mtx[i][j] ; }
double operator() ( std::size_t i, std::size_t j ) const { return mtx[i][j] ; }
std::size_t num_rows() const { return mtx.size() ; }
std::size_t num_colss() const { return mtx.empty() ? 0 : mtx.front().size() ; }
private: std::vector<std::vector<double> > mtx;
friend std::ostream &operator<<( std::ostream& out, const Matrix& matrix )
{
for( const auto& row : matrix.mtx )
{
for( double v : row ) out << std::setw(10) << v ;
out << '\n' ;
}
return out ;
}
};
int main()
{
// 4 rows x 7 cols
const Matrix mtx { { 10, 11, 12 }, { 20, 21 }, { 30, 31, 32, 33, 34, 35, 36 }, {}, {40} } ;
std::cout << std::fixed << std::setprecision(1) << mtx << '\n' ;
}
|