[C/C++] 变量交换的方法总结_Jakon
<0> 最简方法
这应该是我们学到的第一种变量交换的方法,直接在主函数里借用第三个变量,实现双变量交换。同理,三变量交换就需要第四个变量,以此类推。
- #include <bits/stdc++.h>
- using namespace std;
-
- int main(void)
- {
- int x, y;
- cin >> x >> y;
- printf("original: x = %%d, y = %%d
", x, y);
- int t = x;
- x = y;
- y = t;
- printf("now: x = %%d, y = %%d
", x, y);
-
- return 0;
-
- }
运行如下:
<1> 自定义函数+指针
自定义函数,这是我的习惯写法,这样可以一进来就看到主函数,在用到自定义函数时再往下详细查看。
此处以int型为例,其他类型只需稍作修改。
- #include <bits/stdc++.h>
- using namespace std;
-
- void iswap(int* x, int* y); //"void"说明无返回值
- int main(void)
- {
- int x, y;
- cin >> x >> y;
- printf("original: x = %%d, y = %%d
", x, y);
- iswap(&x, &y);
- printf("now: x = %%d, y = %%d
", x, y);
-
- return 0;
- }
-
- void iswap(int* x, int* y)
- {
- int t = *x;
- *x = *y;
- *y = t;
- }
-
运行如下:
<2> 自定义函数+传引用
C++提供了"引用",用这样的方法写出的函数看起来、用起来都更加自然。
- #include <bits/stdc++.h>
- using namespace std;
-
- void iswap(int& x, int& y); //"*"改为"&"
- int main(void)
- {
- int x, y;
- cin >> x >> y;
- printf("original: x = %%d, y = %%d
", x, y);
- iswap(x, y); //无需"&"取地址
- printf("now: x = %%d, y = %%d
", x, y);
-
- return 0;
- }
-
- void iswap(int& x, int& y)
- {
- int t = x; //无需"*"
- x = y;
- y = t;
- }
-
运行如下:
推荐阅读