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 <iomanip>
#include <vector>
#include <iterator>
class Matrix
{
public:
typedef std::vector<int> container_type;
Matrix( std::size_t rows, std::size_t columns, int value=0 )
: _rows(rows), _cols(columns), _data(_rows*_cols, value) {}
template <typename ContainerIter>
Matrix( ContainerIter begin, ContainerIter end, std::size_t rows, std::size_t cols )
: _rows(rows), _cols(cols), _data(begin, end) {}
int operator()(std::size_t row, std::size_t col) const
{ return _data[row * _cols + col] ; }
int& operator()(std::size_t row, std::size_t col)
{ return _data[row * _cols + col] ; }
std::size_t rows() const { return _rows ; }
std::size_t cols() const { return _cols ; }
private:
size_t _rows ;
size_t _cols ;
container_type _data ;
};
void print(const Matrix& m)
{
for ( unsigned i=0; i<m.rows(); ++i )
{
for ( unsigned j=0; j<m.cols(); ++j )
std::cout << std::setw(5) << m(i,j) ;
std::cout << '\n' ;
}
std::cout << std::endl ;
}
int main()
{
Matrix matrix(5,4) ;
print(matrix) ;
for ( unsigned r=0; r<matrix.rows(); ++r )
for ( unsigned c=0; c<matrix.cols(); ++c )
matrix(r,c) = (r+1)*(c+1) ;
print(matrix) ;
int array[]={1,2,3,4,5,6,7,8};
std::size_t arrayElements = sizeof(array) / sizeof(array[0]) ;
Matrix m(array, array+arrayElements, 2, 4) ;
print(m) ;
}
|