采用c++实现
实现方法一(引用):
#include<iostream>
using namespace std;
//交换函数的声明(引用方式)
void swap(int& x, int& y);
int main()
{
int a, b;
a = 1;
b = 10;
cout << "a = " << a << ", b = " << b << endl;
swap(a, b);
cout << "a = " << a << ", b = " << b << endl;
return 0;
}
void swap(int& x, int& y)
{
int temp; //声明一个中间变量
temp = x;
x = y;
y = temp;
}
结果:
实现方法二(指针):
#include<iostream>
using namespace std;
//交换函数的声明(指针方式)
void swap(int* x, int* y);
int main()
{
int a, b;
a = 1;
b = 10;
cout << "a = " << a << ", b = " << b << endl;
swap(&a, &b);
cout << "a = " << a << ", b = " << b << endl;
return 0;
}
void swap(int* x, int* y)
{
int temp; //声明一个中间变量
temp = *x;
*x = *y;
*y = temp;
}
结果:
实现方法三(宏函数):
#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 << "a = " << a << ", b = " << b << endl;
SWAP(a, b, temp);
cout << "a = " << a << ", b = " << b << endl;
return 0;
}
结果:
实现方法四(内置模板函数):
#include<iostream>
using namespace std;
int main()
{
int a, b;
a = 1;
b = 10;
cout << "a = " << a << ", b = " << b << endl;
std::swap(a, b);
cout << "a = " << a << ", b = " << b << endl;
return 0;
}
结果: