在学习北京大学教授的《程序设计实习 / Practice on Programming》中,遇到了一个习题,花了很长时间研究,现在分享出来:
课题地址:https://class.coursera.org/pkupop-001/human_grading/view/courses/972168/assessments/9/submissions
课题描述:
实现一个三维数组模版CArray3D,可以用来生成元素为任意类型变量的三维数组,使得下面程序输出结果是: 0,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, 注意,只能写一个类模版,不能写多个 int main() { CArray3D<int> a(3,4,5); int No = 0; for( int i = 0; i < 3; ++ i ) for( int j = 0; j < 4; ++j ) for( int k = 0; k < 5; ++k ) a[i][j][k] = No ++; for( int i = 0; i < 3; ++ i ) for( int j = 0; j < 4; ++j ) for( int k = 0; k < 5; ++k ) cout << a[i][j][k] << ","; return 0; } 提示:类里面可以定义类,类模版里面也可以定理类模版。例如: class A { class B { }; }; template <class T> class S { T x; class K { T a; }; };
课题实现代码:
难点:用set函数实现赋值(开始一直用构造函数实现,需要定义指针的指针)
#include <iostream> using namespace std; template <class T> class CArray3D { template <class T> class CArray2D { template <class T> class CArray1D { public: CArray1D():p(NULL){} void set(T a) { p = new T[a]; _a = a; } inline T& operator[]( long elem ) const { // assert( elem >= 0 && elem < _a ); return p[elem]; } ~CArray1D() { delete[] p; }; private: T* p; T _a; }; public: CArray2D():p(NULL){} void set(T a, T b){ p = new CArray1D<T>[a]; for(int i=0; i<a; i++){ p[i].set(b); } _b = b; } inline CArray1D<T>& operator[]( long elem ) const { // assert( elem >= 0 && elem < _b ); return p[elem]; } ~CArray2D() { delete[] p; } private: CArray1D<T>* p; T _b; }; public: CArray3D(T a, T b, T c){ p = new CArray2D<T>[a]; for(int i=0; i<a; i++){ p[i].set(b, c); } _c = c; } inline CArray2D<T>& operator[]( long elem ) const { // assert( elem >= 0 && elem < _c ); return p[elem]; } ~CArray3D() { delete[] p; } private: CArray2D<T>* p; T _c; }; int main() { CArray3D<int> a(3,4,5); int No = 0; for( int i = 0; i < 3; ++ i ) for( int j = 0; j < 4; ++j ) for( int k = 0; k < 5; ++k ) a[i][j][k] = No ++; for( int i = 0; i < 3; ++ i ) for( int j = 0; j < 4; ++j ) for( int k = 0; k < 5; ++k ) cout << a[i][j][k] << ","; return 0; }