一.题目描述
用函数模板实现数据交换(考察引用和函数模板)
Description
设计函数模板Swap,能够实现整型数与整型数、浮点型数与浮点型数、字符串与字符串的交换。
Input
int main()
{
int a, b;
double x, y;
string str1, str2;
cin >> a >> b;
cin >> x >> y;
cin >> str1 >> str2;
Swap(a, b);
Swap(x, y);
Swap(str1, str2);
cout << a << " " << b << endl;
cout << x << " " << y << endl;
cout << str1 << " " << str2 << endl;
return 0;
}
Output
分别输出交换后的整型数、浮点型数和字符串。
二.输入与输出
Sample Input 1
100 200 21.5 31.4 asdfqw iyjl
Sample Output 1
200 100 31.4 21.5 iyjl asdfqw
三.代码
#include<bits/stdc++.h>
using namespace std;
template<class T>
void Swap(T&x,T&y){
T tmp = x;
x = y;
y = tmp;
}
int main()
{
int a, b;
double x, y;
string str1, str2;
cin >> a >> b;
cin >> x >> y;
cin >> str1 >> str2;
Swap(a, b);
Swap(x, y);
Swap(str1, str2);
cout << a << " " << b << endl;
cout << x << " " << y << endl;
cout << str1 << " " << str2 << endl;
return 0;
}