C++技巧之二维动态数组类模板
作者 佚名技术
来源 程序设计
浏览
发布时间 2012-06-29
template <typename T> ostream& operator<<(ostream& os, const Array<T>& array) { for(int i=0; i<array.size; ++i) { os<<array.data[i]<<"\t"; } return os; } #endif 第二个头文件Array2D.h是二维动态数组类模板: //Array2D.h #ifndef CARL_SEN_ARRAY2D_H #define CARL_SEN_ARRAY2D_H #include "Array.h" #include <iostream> #include <cstdarg> using std::ostream; using std::out_of_range; template <typename T> class Array2D { protected: unsigned int rows; unsigned int cols; Array<T> array; public: //构造函数 Array2D(unsigned int _rows=0, unsigned int _cols=0); Array2D(unsigned int _rows, unsigned int _cols, T data1, ...); //两种重载运算符 class RowArray; RowArray operator[](unsigned int row); const RowArray operator[](unsigned int row) const; friend ostream& operator<<(ostream& os, const Array2D<T>& array2D); //计算第二维下标操作的嵌套类 class RowArray { private: const Array2D<T>& array2D; unsigned int row; public: RowArray(Array2D<T>& _array2D, unsigned int _row=0): array2D(_array2D), row(_row) {} RowArray(const Array2D<T>& _array2D, unsigned int _row=0): array2D(_array2D), row(_row) {} T& operator[](unsigned int col) { if(col>=array2D.cols) { throw out_of_range("invalid col"); } return const_cast<Array2D<T>&>(array2D).array[row*array2D.cols+col]; } const T& operator[](unsigned int col) const { if(col>=array2D.cols) { throw out_of_range("invalid col"); } return array2D.array[row*array2D.cols+col]; } }; friend class RowArray; //get,set函数 unsigned int getRows() const { return rows; } unsigned int getCols() const { return cols; } }; template <typename T> Array2D<T>::Array2D(unsigned int _rows, unsigned int _cols): rows(_rows), cols(_cols), array(_rows*_cols){ for(unsigned int i=0; i<rows*cols; ++i) { array[i]=T(); } } template <typename T> Array2D<T>::Array2D(unsigned int _rows, unsigned int _cols, T data1, ...): rows(_rows), cols(_cols),array(_rows*_cols){ va_list ap; va_start(ap, _cols); for(unsigned int i=0; i<rows*cols; ++i) { array[i]=va_arg(ap, T); } va_end(ap); } template <typename T> Array2D<T>::RowArray Array2D<T>::operator[](unsigned int row) { if(row>=rows) { throw out_of_range("invalid row"); } return RowArray(*this, row); } template <typename T> const Array2D<T>::RowArray Array2D<T>::operator[](unsigned int row) const { if(row>=rows) { throw out_of_range("invalid row"); } return RowArray(*this, row); } template <typename T> ostream& operator<<(ostream& os, const Array2D<T>& array2D) { unsigned int i, j; for(i=0; i<array2D.rows; ++i) { for(j=0; j<array2D.cols; ++j) { os<<array2D.array[i*array2D.cols+j]<<"\t"; } if(i!=array2D.rows-1) { os<<endl; } } return os; } #endif 现在就可以使用它们了,如下 |
凌众科技专业提供服务器租用、服务器托管、企业邮局、虚拟主机等服务,公司网站:http://www.lingzhong.cn 为了给广大客户了解更多的技术信息,本技术文章收集来源于网络,凌众科技尊重文章作者的版权,如果有涉及你的版权有必要删除你的文章,请和我们联系。以上信息与文章正文是不可分割的一部分,如果您要转载本文章,请保留以上信息,谢谢! |