博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

交换两个变量的函数

Posted on 2011-06-15 16:58  hackbuteers  阅读(293)  评论(0)    收藏  举报

第一种方法:使用指针来交换两个变量

1 #include "iostream"
2 using namespace std;
3
4 void my_swap(int *a,int *b) //使用指针来交换两个变量
5 {
6 int temp;
7 if(*a>*b)
8 {
9 temp=*a;
10 *a=*b;
11 *b=temp;
12 }
13 return ;
14 }
15
16 void main()
17 {
18 int a[]={32,12};
19 my_swap(&a[0],&a[1]); //使用指针
20 printf("%d %d\n",a[0],a[1]);
21 system("pause");
22 }

第二种方法:使用引用来交换两个变量

1 #include "iostream"
2 using namespace std;
3
4 void my_swap(int &a,int &b) //使用引用来交换两个变量
5 {
6 int temp;
7 if(a>b)
8 {
9 temp=a;
10 a=b;
11 b=temp;
12 }
13 return ;
14 }
15 void main()
16 {
17 int a[]={32,12};
18 my_swap(a[0],a[1]); //使用引用
19 printf("%d %d\n",a[0],a[1]);
20 system("pause");
21 }