• 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 }
  • 相关阅读:
    mysql索引批量在postgres里面重建
    获取metabase用户信息
    metabase一个sql统计
    C笔记-左值与右值
    前端散记(不定时补充)
    推荐一本书 保险进行时
    怎么增加照片的KB大小
    Java 流(Stream)、文件(File)和IO
    Java HashMap 和 ConcurrentHashMap 以及JDK 1.7 和 1.8 的区别
    【一文整理:Google Big table 序列化组件 Protocol Buffers 的使用 】
  • 原文地址:https://www.cnblogs.com/Froger/p/6771664.html
Copyright © 2020-2023  润新知