G 类模板
时间: 1ms 内存:128M
描述:
声明一个类模板,类模板中有2个相同类型的数据成员,有一函数来完成这两个成员从小到大的输出。
类模板声明如下:
template<class T> //T为虚拟类型
class MyTemp
{
public:
MyTemp(T a,T b);
void orderprint();
private:
T x;
T y;
};请在下面的程序段基础上完成整个设计
#include <iostream>
using namespace std;template<class T> //类模版声明
class MyTemp
{
public:
MyTemp(T a,T b);
void orderprint();
private:
T x;
T y;
};//将程序需要的其他成份写在下面,只提交begin到end部分的代码
//******************** begin ********************
//********************* end ********************
int main()
{
int i1,i2;
cin>>i1>>i2; //输入两个整数
MyTemp<int> temp1(i1,i2);
temp1.orderprint();double d1,d2;
cin>>d1>>d2; //输入两个浮点小数
MyTemp<double> temp2(d1,d2);
temp2.orderprint();char c1,c2;
cin>>c1>>c2; //输入两个字符
MyTemp<char> temp3(c1,c2);
temp3.orderprint();return 0;
}
输入:
2个整数
2个浮点数
2个字符
输出:
从小到大输出2个整数
从小到大输出2个浮点数
从小到大输出2个字符
示例输入:
9 5
1.1 3.4
c a
示例输出:
5 9
1.1 3.4
a c
提示:
参考答案(内存最优[1092]):
#include<stdio.h>
int main()
{
int a,b;
float c,d;
char e[4],*p,f[4],*q;
scanf("%d %d",&a,&b);
if(a<b)
printf("%d %d\n",a,b);
else
printf("%d %d\n",b,a);
scanf("%f %f",&c,&d);
if(c<d)
printf("%.1f %.1f\n",c,d);
else
printf("%.1f %.1f\n",d,c);
scanf("%s",e);
scanf("%s",f);
p=&e[0];
q=&f[0];
if(*p<*q)
printf("%c %c\n",*p,*q);
else
printf("%c %c\n",*q,*p);
}
参考答案(时间最优[0]):
#include <iostream>
using namespace std;
template<class T> //类模版声明
class MyTemp
{
public:
MyTemp(T a,T b);
void orderprint();
private:
T x;
T y;
};
//将程序需要的其他成份写在下面,只提交begin到end部分的代码
//******************** begin ********************
template<class T>
MyTemp<T>::MyTemp(T a,T b)
{
x=a;
y=b;
}
template<class T>
void MyTemp<T>::orderprint()
{
if(x>y)
cout<<y<<" "<<x<<endl;
else
cout<<x<<" "<<y<<endl;
}
//********************* end ********************
int main()
{
int i1,i2;
cin>>i1>>i2; //输入两个整数
MyTemp<int> temp1(i1,i2);
temp1.orderprint();
double d1,d2;
cin>>d1>>d2; //输入两个浮点小数
MyTemp<double> temp2(d1,d2);
temp2.orderprint();
char c1,c2;
cin>>c1>>c2; //输入两个字符
MyTemp<char> temp3(c1,c2);
temp3.orderprint();
return 0;
}
题目和答案均来自于互联网,仅供参考,如有问题请联系管理员修改或删除。