WHCSRL 技术网

[C/C++] 变量交换的方法总结_Jakon

<0> 最简方法

这应该是我们学到的第一种变量交换的方法,直接在主函数里借用第三个变量,实现双变量交换。同理,三变量交换就需要第四个变量,以此类推。

  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. int main(void)
  4. {
  5. int x, y;
  6. cin >> x >> y;
  7. printf("original: x = %%d, y = %%d ", x, y);
  8. int t = x;
  9. x = y;
  10. y = t;
  11. printf("now: x = %%d, y = %%d ", x, y);
  12. return 0;
  13. }

运行如下:

<1>  自定义函数+指针

自定义函数,这是我的习惯写法,这样可以一进来就看到主函数,在用到自定义函数时再往下详细查看。

此处以int型为例,其他类型只需稍作修改。

  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. void iswap(int* x, int* y); //"void"说明无返回值
  4. int main(void)
  5. {
  6. int x, y;
  7. cin >> x >> y;
  8. printf("original: x = %%d, y = %%d ", x, y);
  9. iswap(&x, &y);
  10. printf("now: x = %%d, y = %%d ", x, y);
  11. return 0;
  12. }
  13. void iswap(int* x, int* y)
  14. {
  15. int t = *x;
  16. *x = *y;
  17. *y = t;
  18. }

运行如下:

<2> 自定义函数+传引用

C++提供了"引用",用这样的方法写出的函数看起来、用起来都更加自然。

  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. void iswap(int& x, int& y); //"*"改为"&"
  4. int main(void)
  5. {
  6. int x, y;
  7. cin >> x >> y;
  8. printf("original: x = %%d, y = %%d ", x, y);
  9. iswap(x, y); //无需"&"取地址
  10. printf("now: x = %%d, y = %%d ", x, y);
  11. return 0;
  12. }
  13. void iswap(int& x, int& y)
  14. {
  15. int t = x; //无需"*"
  16. x = y;
  17. y = t;
  18. }

运行如下:

推荐阅读