算法复习--------------二维数组

来源:互联网 发布:最好的聊天交友软件 编辑:程序博客网 时间:2024/06/07 14:01

二维数组的实现是建立在一个数组的基础上的,通过一个一维数组的指针来保存二维数组的行, 但是可以通过cols来控制每一行的个数

具体实现代码如下:

#include "ClassArray1D.h"template<class T>class Array2D{private:int rows, cols;Array1D<T> * row; public:Array2D(int r = 0, int col = 0);  //构造函数Array2D(const Array2D<T> & v);//复制构造函数~Array2D(); //析构函数int GetRows()const{ return rows; }  //获取行int GetCols()const{ return cols; }  //获取列Array1D<T>& operator[](int i)const;  //下表操作,获取第几行Array2D<T>& operator=(const Array2D<T> &m); Array2D<T> operator+()const;Array2D<T> operator+(const Array2D<T>& m)const;Array2D<T> operator-()const;Array2D<T> operator-(const Array2D<T>& m)const;Array2D<T> operator*(const Array2D<T>& m)const;Array2D<T> operator+=(const T& x);};template<class T>Array2D<T>::Array2D(int r, int c){if (r < 0 || c < 0)throw;if ((!r || !c) && (r || c))throw;rows = r;cols = c;row = new Array1D<T>[r];for (int i = 0; i < r; i++){row->ReSize(c);}}template<class T>Array2D<T>::Array2D(const Array2D<T>& m){rows = m.rows;cols = m.clos;row = new Array1D<T>[rows];for (int i = 0; i < rows; i++){row[i] = m.row[i];}}template<class T>Array1D<T>& Array2D<T>::operator[](int i)const{if (i < 0 || i >= rows) throw;return row[i];}template<class T>Array2D<T> Array2D<T>::operator-(const Array2D<T>& m)const{if (rows != m.rows || cols != m.cols) throw;Array2D<T> w(rows, cols);for (int i = 0; i < rows; i++){w.row[i] = row[i] - m.row[i];}return w;}template<class T>Array2D<T> Array2D<T>::operator+(const Array2D<T>& m)const{if (rows != m.rows || cols != m.cols) throw;Array2D<T> w(rows, cols);for (int i = 0; i < rows; i++){w.row[i] = row[i] + m.row[i];}return w;}template<class T>Array2D<T> Array2D<T>::operator-()const{Array2D<T> w(rows, cols);for (int i = 0; i < rows; i++){w.row[i] = -row[i];}return w;}template<class T>Array2D<T> Array2D<T>::operator+()const{Array2D<T> w(rows, cols);for (int i = 0; i < rows; i++){w.row[i] = row[i];}return w;}template<class T>Array2D<T> Array2D<T>::operator+=(const T& x){Array2D<T> w(rows, cols);for (int i = 0; i < rows; i++){w.row[i] = row[i] + x;}return w;}template<class T>Array2D<T> Array2D<T>::operator*(const Array2D<T>& m)const{if (cols != m.cols)throw;Array2D<T> w(rows, cols);for (int i = 0; i < rows; i++){for (int j = 0; j < m.cols; j++){T sum = (*this)[i][0] * m[0][j];for (int k = 1; k < cols; k++)sum += (*this)[i][k] * m[k][j];w[i][j] = sum;}}return w;}


0 0