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
|
#include <iostream>
#include <vector>
struct matrix
{
matrix( std::size_t nrows, std::size_t ncols, double v = 0 )
: data( nrows, std::vector<double>( ncols, v ) ) {}
matrix( std::initializer_list< std::initializer_list<double> > ilist )
: data( ilist.begin(), ilist.end() )
{
std::size_t max_cols = 0 ;
for( const auto& row : data ) max_cols = std::max( max_cols, row.size() ) ;
for( auto& row : data ) row.resize( max_cols ) ;
}
std::size_t num_rows() const { return data.size() ; }
std::size_t num_cols() const { return data.empty() ? 0 : data[0].size() ; }
matrix& operator+= ( double value )
{
for( auto& row : data ) for( double& v : row ) v += value ;
return *this ;
}
// etc.
auto& operator[] ( std::size_t row ) { return data[row] ; }
const auto& operator[] ( std::size_t row ) const { return data[row] ; }
// etc.
private: std::vector< std::vector<double> > data ;
};
matrix operator+ ( matrix m, double d ) { return m += d ; }
matrix operator+ ( double d, const matrix& m ) { return m + d ; }
// etc.
int main()
{
matrix mtx { { 1.0, 2.0, 3.0 }, { 4.0, 5.0, 6.0, 7.0 }, { 8.0, 9.0 } } ;
for( std::size_t i = 0 ; i < mtx.num_rows() ; ++i )
{
for( std::size_t j = 0 ; j < mtx.num_cols() ; ++j )
std::cout << std::fixed << mtx[i][j] << ' ' ;
std::cout << '\n' ;
}
std::cout << '\n' ;
mtx = 100 + mtx ;
for( std::size_t i = 0 ; i < mtx.num_rows() ; ++i )
{
for( std::size_t j = 0 ; j < mtx.num_cols() ; ++j )
std::cout << std::fixed << mtx[i][j] << ' ' ;
std::cout << '\n' ;
}
}
|