zoukankan      html  css  js  c++  java
  • 1交换算法

      1 //交换算法
      2 
      3 #include "swap.h"
      4 #include <stdio.h>
      5 #include <iostream>
      6 
      7 
      8 using namespace std;
      9 #define swap_m(x,y,t) ((t)=(x),(x)=(y),(y)=(t))        // #define后面不要加 分号;
     10 void swap(int x,int y);
     11 void swap_p(int *px,int *py);
     12 void swap_r(int &rx,int &ry);
     13 
     14 int main()
     15 {
     16     int a,b,temp;
     17     a=1;
     18     b=10;
     19     printf("交换前:a=%d,b=%d
    
    
    ",a,b);
     20 
     21     //方法1
     22     printf("通过临时变量交换---->完成值传递交换
    ");
     23     temp=a;
     24     a=b;
     25     b=temp;
     26     printf("交换后:a=%d,b=%d
    
    
    ",a,b);
     27 
     28     //方法2
     29     a=1;
     30     b=10;
     31     swap(a,b);
     32     printf("交换后:a=%d,b=%d
    
    
    ",a,b);
     33 
     34     //方法3
     35     a=1;
     36     b=10;
     37     swap_p(&a,&b);//不要忘记&符号
     38     printf("交换后:a=%d,b=%d
    
    
    ",a,b);
     39 
     40     //方法4
     41     printf("通过define宏交换---->完成值传递交换
    ");
     42     a=1;
     43     b=10;
     44     swap_m(a,b,temp);
     45     printf("交换后:a=%d,b=%d
    
    
    ",a,b);
     46 
     47 
     48     //方法5      printf("通过引用交换----->完成实参交换
    
    
    ");
     49     a=1;
     50     b=10;
     51     swap_r(a,b);
     52     printf("交换后:a=%d,b=%d
    
    
    ",a,b);
     53 
     54     //方法6
     55     printf("实用C++模板
    ");
     56     a=1;
     57     b=10;
     58     std::swap(a,b);
     59     printf("交换后:a=%d,b=%d
    
    
    ",a,b);
     60 
     61     printf("hello world...
    ");
     62     system("pause");
     63     return 0;
     64 }
     65 
     66 //默认按值传递,所以只会传a,b的拷贝,不会修改a,b本身
     67 void swap(int x,int y)
     68 {
     69     int temp;
     70     temp = x;
     71     x = y;
     72     y =temp;
     73     printf("拷贝---->完成值传递交换
    ");
     74 }
     75 
     76 
     77 //指针也是值传递,只不过形参和实参指向的都是同一个内存地址,所以才能够修改实参的值...记住了哦
     78 void swap_p(int *px,int *py)
     79 {
     80     int temp;
     81     temp = *px;
     82     *px = *py;
     83     *py = temp;
     84     printf("指针---->完成值传递交换
    ");
     85 }
     86 
     87 
     88 //引用,可以直接修改实参的数据
     89 void swap_r(int &rx,int &ry)
     90 {
     91 
     92     int temp;
     93     temp=rx;
     94     rx = ry;
     95     ry=temp;
     96     printf("引用---->可以直接修改实参的数据
    ");
     97 
     98 
     99     return;
    100 }
  • 相关阅读:
    BZOJ3413: 匹配
    BZOJ5084: hashit
    BZOJ2281: [Sdoi2011]黑白棋
    BZOJ4808: 马
    BZOJ3208: 花神的秒题计划Ⅰ
    BZOJ3714: [PA2014]Kuglarz
    BZOJ2102: [Usaco2010 Dec]The Trough Game
    JZOJ6676. 【2020.06.01省选模拟】查拉图斯特拉如是说 (第二类斯特林数+多项式多点求值)
    LOJ #3217. 「PA 2019」Desant(状压dp)
    JZOJ 5154.【NOI2017模拟6.20】树形图求和 (矩阵树定理)
  • 原文地址:https://www.cnblogs.com/Froger/p/6771664.html
Copyright © 2011-2022 走看看