2 <Spawn> Динамический массив позволяет программно менять размеры.
2 Гость_Djnv Топик негодится.
| Код | template<class T> class matrixd // она же двумерный массив { T *base; int row_count, col_count; int linear_idx(int row, int col) const { return (row * get_col_count() + col); } bool is_valid_idx(int row, int col) const { if(row >= get_row_count()) //out of bounds return false; if(col >= get_col_count()) return false; return true; } void assign_(const matrixd &r); void free(void) { resize(0, 0); } static T access_error; public: matrixd(void) : base(NULL), row_count(0), col_count(0) { } explicit matrixd(const matrixd &r) : base(NULL), row_count(0), col_count(0) { assign_(r); } const matrixd& operator=(const matrixd &r) { assign_(r); return *this; } virtual ~matrixd(void) { free(); }
int get_row_count(void) const { return row_count; } int get_col_count(void) const { return col_count; } int get_count(void) const { return (row_count * col_count); }
void resize(int row_count, int col_count); T& operator()(int row, int col) { if(!is_valid_idx(row, col)) return access_error; return base[linear_idx(row, col)]; } const T& operator()(int row, int col) const { if(!is_valid_idx(row, col)) return access_error; return base[linear_idx(row, col)]; }
};
template<class T> T matrixd<T>::access_error;
template<class T> void matrixd<T>::assign_(const matrixd &r) { resize(r.get_row_count(), r.get_col_count()); int c=get_count(); for(int i=0; i<c; ++i) base[i] = r.base[i]; }
template<class T> void matrixd<T>::resize(int new_row_count, int new_col_count) { int count = row_count*col_count; int new_count = new_row_count*new_col_count; if(count != new_count) { if(count != 0) { delete[] base; // free base = NULL; row_count = 0; col_count = 0; } if(new_count != 0) { count = new_count; base = new T[count]; // allocate row_count = new_row_count; col_count = new_col_count; } } }
// использование { matrixd<float> m; m.resize(10, 20);
m(2,2)=1.2345; //... }
|
wbr. |