1.使用三个变量,相互交换
#include <iostream>
using namespace std;
int main()
{
int a, b, tmp;
a = 1;
b = 10;
cout << "交换之前" << endl;
cout << "a = " << a << ", b = " << b << endl;
tmp = a;//交换
a = b;
b = tmp;
cout << "交换之后" << endl;
cout << "a = " << a << ", b = " << b << endl;
system("pause");
return 0;
}
2.按值传递,不成功
#include<iostream>
using namespace std;
void swap(int x, int y);
int main()
{
int a, b;
a = 1;
b = 10;
cout << "使用void swap(int x, int y)" << endl;
cout << "一个不成功的方法:" << endl;
cout << "a = " << a << ", b =" << b << endl;
swap(a, b);//按值传递,拷贝值,传进函数
cout << "a = " << a << ", b = " << b << endl;
system("pause");
return 0;
}
void swap(int x, int y)
{
int tmp;
tmp = x;
x = y;
y = tmp;
}
3.使用指针
#include <iostream>
using namespace std;
void swap(int *px, int *py);
int main()
{
int a, b;
a = 1;
b = 10;
cout << "使用指针的方法:" << endl;
cout << "a = " << a << ", b = " << b << endl;
swap(&a, &b);//传地址
cout << "a = " << a << ", b = " << b << endl;
system("pause");
return 0;
}
void swap(int *px, int *py)
{
int tmp;
tmp = *px;
*px = *py;
*py = tmp;
}
4.使用宏定义函数
#include <iostream>
#define SWAP(x,y,t) ((t) = (x), (x) = (y), (y) = (t))//函数名一般使用大写字母
using namespace std;
int main()
{
int a, b, temp;
a = 1;
b = 10;
cout << "使用宏定义函数:" << endl;
cout << "a = " << a << ", b = " << b << endl;
SWAP(a, b, temp);
cout << "a = " << a << ",b = " << b << endl;
system("pause");
return 0;
}
5.使用引用
#include <iostream>
using namespace std;
void swap(int &x, int &y);
int main()
{
int a, b;
a = 1;
b = 10;
cout << "使用引用交换:" << endl;
cout << "a = " << a << ", b =" << b << endl;
swap(a, b);
cout << "a = " << a << ", b =" << b << endl;
system("pause");
return 0;
}
//引用就是别名
void swap(int &x, int &y)
{
int tmp;
tmp = x;
x = y;
y = tmp;
}
6.使用模板函数
#include<iostream>
using namespace std;
int main()
{
int a, b;
a = 1;
b = 10;
cout << "使用std::swap" << endl;
std::swap(a, b);
cout << "a = " << a << ", b=" << b<< endl;
system("pause");
return 0;
}
总结:模板函数对各种类型的变量收可以交换,自己定义的函数只能对相应的类型交换,C语言里面可以使用传指针和宏定义函数
void swap(int *px, int *py)\\传指针
#define SWAP(x,y,t) ((t) = (x), (x) = (y), (y) = (t))//宏定义函数
C++里面可以使用引用和模板函数
void swap(int &x, int &y)\\引用
template<class T> void swap(T& x,T& b)\\模板函数
注意按值传递的函数不能实现交换。