30 模板类练习:实现两个整数、浮点数和字符的比较
作者: 冯向阳时间限制: 1S章节: 类与对象
问题描述 :
请定义一个类模板,利用它分别实现两个整数、浮点数和字符串的比较。在main函数中应用并测试之。
输入说明 :
每组输出分3行:
第一行:标志行('i'代表输入两个整数进行比较;'f'代表输入两个浮点数进行比较;'s'代表输入两个字符串进行比较;'e'代表输入结束。)
第二行和第三行分别对应进行比较的两个数据
输入行之间无多余的空行,每行的开头和结尾无多余的空格
输入可连续进行。
输出说明 :
每组输入数据对应一行输出数据,为2个比较数据之中的较大者。
组与组的输出行之间无多余的空行,每行的开头和结尾无多余的空格。
#include <iostream>
#include <string>
using namespace std;
// 类模板Comparator
template <typename T>
class Comparator
{
public:
// 比较两个值,返回较大者
T compare(T a, T b)
{
return (a > b) ? a : b;
}
};
int main()
{
char type;
Comparator<int> intComp;
Comparator<float> floatComp;
Comparator<string> stringComp;
while (cin >> type && type != 'e')
{
if (type == 'i')
{
int a, b;
cin >> a >> b;
cout << intComp.compare(a, b) << endl;
}
else if (type == 'f')
{
float a, b;
cin >> a >> b;
cout << floatComp.compare(a, b) << endl;
}
else if (type == 's')
{
string a, b;
cin >> a >> b;
cout << stringComp.compare(a, b) << endl;
}
}
return 0;
}