c++语言编写程序,设计一个函数模板,实现两数的交换,并用int、float、char等类型的数据进行测试
时间: 2024-01-24 11:17:27 浏览: 73
C语言程序设计-编写函数实现两个数据的交换,在主函数中输入任意三个数据,调用函数对这三个数据从大到小排序;.c
5星 · 资源好评率100%
下面是一个使用函数模板实现两数交换的例子:
```c++
#include <iostream>
using namespace std;
template <typename T>
void swap(T& a, T& b)
{
T temp = a;
a = b;
b = temp;
}
int main()
{
int x = 1, y = 2;
float a = 1.5, b = 2.5;
char c1 = 'a', c2 = 'b';
cout << "Before swap: x=" << x << ", y=" << y << endl;
swap(x, y);
cout << "After swap: x=" << x << ", y=" << y << endl;
cout << "Before swap: a=" << a << ", b=" << b << endl;
swap(a, b);
cout << "After swap: a=" << a << ", b=" << b << endl;
cout << "Before swap: c1=" << c1 << ", c2=" << c2 << endl;
swap(c1, c2);
cout << "After swap: c1=" << c1 << ", c2=" << c2 << endl;
return 0;
}
```
输出结果为:
```
Before swap: x=1, y=2
After swap: x=2, y=1
Before swap: a=1.5, b=2.5
After swap: a=2.5, b=1.5
Before swap: c1=a, c2=b
After swap: c1=b, c2=a
```
可以看到,通过函数模板实现的swap函数可以用于多种类型的数据,并且能够达到正确的交换效果。
阅读全文