编程题#1
来源: POJ (Coursera声明:在POJ上完成的习题将不会计入Coursera的最后成绩。)
注意: 总时间限制: 1000ms 内存限制: 65536kB
描述
实现一个三维数组模版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,
注意,只能写一个类模版,不能写多个。
#include <iostream> using namespace std; // 在此处补充你的代码 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; }
输入
无
输出
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,
样例输入
无
样例输出
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,
提示
提示:类里面可以定义类,类模版里面也可以定义类模版。例如:
class A { class B { }; }; template class S { T x; class K { T a; }; };
1 #include <iostream> 2 using namespace std; 3 // 在此处补充你的代码 4 template <class T> 5 class CArray3D { 6 public: 7 template <class T1> 8 class CArray2D { 9 private: 10 T1 *a; 11 int i,j; 12 public: 13 CArray2D() {a = NULL;} 14 CArray2D(int a1, int a2):i(a1),j(a2) { 15 a = new T1[i*j]; 16 } 17 ~CArray2D() { 18 if (a != NULL) delete []a; 19 } 20 T1 *operator[](int a1) { 21 return a + a1*j; 22 } 23 }; 24 CArray3D() {array2D = NULL;} 25 CArray3D(int a1, int a2, int a3) { 26 array2D = new CArray2D<T>*[a1]; 27 for (int m = 0; m < a1; ++m) { 28 array2D[m] = new CArray2D<T>(a2, a3); 29 } 30 } 31 CArray2D<T> &operator[](int i) { 32 return *array2D[i]; 33 } 34 ~CArray3D() { 35 if (array2D != NULL) delete []array2D; 36 } 37 private: 38 CArray2D<T> **array2D; 39 }; 40 int main() 41 { 42 CArray3D<int> a(3,4,5); 43 int No = 0; 44 for( int i = 0; i < 3; ++ i ) 45 for( int j = 0; j < 4; ++j ) 46 for( int k = 0; k < 5; ++k ) 47 a[i][j][k] = No ++; 48 for( int i = 0; i < 3; ++ i ) 49 for( int j = 0; j < 4; ++j ) 50 for( int k = 0; k < 5; ++k ) 51 cout << a[i][j][k] << ","; 52 return 0; 53 }