Tip
在C++中,可以使用引用来替换指针,例如:
void swap(int &a, int &b)
{
...
}
int a = 100, b = 200;
swap(a, b);
方法一:使用加减运算符
#include <iostream>
void swap(int *a, int *b)
{
*a = *a + *b;
*b = *a - *b;
*a = *a - *b;
return;
}
int main ()
{
// 局部变量声明
int a = 100;
int b = 200;
std::cout << "交换前,a 的值:" << a << std::endl;
std::cout << "交换前,b 的值:" << b << std::endl;
// 调用函数来交换值
swap(&a, &b);
std::cout << "交换后,a 的值:" << a << std::endl;
std::cout << "交换后,b 的值:" << b << std::endl;
return 0;
}
输出:
u0_a427@localhost ~/p/test> ./test.out
交换前,a 的值:100
交换前,b 的值:200
交换后,a 的值:200
交换后,b 的值:100
u0_a427@localhost ~/p/test>
方法二:使用异或运算
#include <iostream>
void swap(int *a, int *b)
{
*a = *a ^ *b;
*b = *a ^ *b;
*a = *a ^ *b;
return;
}
int main ()
{
// 局部变量声明
int a = 100;
int b = 200;
std::cout << "交换前,a 的值:" << a << std::endl;
std::cout << "交换前,b 的值:" << b << std::endl;
// 调用函数来交换值
swap(&a, &b);
std::cout << "交换后,a 的值:" << a << std::endl;
std::cout << "交换后,b 的值:" << b << std::endl;
return 0;
}
输出:
u0_a427@localhost ~/p/test> ./test.out
交换前,a 的值:100
交换前,b 的值:200
交换后,a 的值:200
交换后,b 的值:100
u0_a427@localhost ~/p/test>
By MeltIce.