c++库函数里已经有swap()这个函数
作用是交换两个数或字符的值
头文件
#include<iostream>
using namespace std;
用法swap(number1,number2);
====
现在自己实现swap()函数交换两整型的值
#include<iostream>
using namespace std;
void swap(int *a,int *b)
{
int temp;
temp=*a;
*a=*b;
*b=temp;
}
int main()
{
int a=9,b=8;
swap(a,b);
cout<<a<<' '<<b;
system("pause");
return 0;
}
下面用函数模板实现swap(),这里的swap可以用来交换 int、float、double、string、char等变量的值
<pre name="code" class="cpp">#include<iostream>
#include<string>
using namespace std;
template<typename T>//函数模板 T是模板参数
T swap(T *a, T *b)
{
T temp;
temp=*a;
*a=*b;
*b=temp;
}
int main()
{
double a=10.1,b=100.9;
swap(a,b); //交换double型变量的值
cout<<a<<' '<<b;
cout<<endl;
system("pause");
return 0;
}效果如下
C++ swap函数详解与模板实现
本文介绍了C++标准库中的swap函数及其用途,并通过示例代码详细讲解了如何手动实现swap函数来交换两个整数的值。此外,还展示了如何使用函数模板来实现通用的swap函数,支持多种数据类型。
2616

被折叠的 条评论
为什么被折叠?



