编程题#1
来源: POJ (http://cxsjsxmooc.openjudge.cn/test/7w6/)
注意: 只提交补充的代码
描述
实现一个三维数组模版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;
};
};
程序解答
#include <iostream>
using namespace std;
// 在此处补充你的代码
template<class T>
class CArray3D{ //定义三维数组************************************
template<class T1>
class CArray2D{ //定义二维数组####################################
template<class T2>
class CArray1D{ //定义一维数组$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
private:
T2 *p; //为第三个维度开辟动态空间k_
public:
void set(int k_){
p = new T2[k_];
}
~CArray1D(){ delete[]p; }
T2& operator[](int i){ return p[i]; }
}; //定义一维数组$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
private:
CArray1D<T1> *p1; //定义指向后面1个维度的指针
public:
void set(int j_, int k_){
p1 = new CArray1D<T1>[j_]; //p1是一个指针,为p1分配j_空间,每一维都是一个一维数组
for (int j = 0; j < j_; j++)
p1[j].set(k_);
}
~CArray2D(){ delete[]p1; }
CArray1D<T1>& operator[](int i){ return p1[i]; }
}; //定义二维数组#################################################
private:
CArray2D<T> *p2; //定义指向后面2个维度的指针
public:
CArray3D(int i_, int j_, int k_){ // i_, j_, k_ 数组的三个维度
p2 = new CArray2D<T>[i_]; //p2是一个指针,为p2分配i_空间,每一维都是一个二维数组
for (int i = 0; i < i_; i++)
p2[i].set(j_, k_);
}
~CArray3D(){ delete[]p2; }
CArray2D<T>& operator[](int i){ return p2[i]; }
}; //定义三维数组*************************************************
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;
}