1、最基本的算法--交换

C/C++中交换算法的几种方式

  1 #include<iostream>
  2 #include<stdlib.h>
  3 
  4 using namespace std;
  5 //第二种方法,定义一个函数
  6 void swap(int x,int y);
  7 //第三种方法,
  8 void swap1(int *px,int *py);
  9 //第四种方法,宏定义
 10 #define SWAP2(x,y,t) ((t)=(x),(x)=(y),(y)=(t))
 11 //第五种方法:C++的引用
 12 //C语言中主要用宏定义,对各种类型都可以交换
 13 //C++中主要用模板函数,对各种类型都可以交换
 14 void swap3(int &x,int &y);
 15 int main()
 16 {
 17 	int a,b,tmp;
 18 	a=5;
 19 	b=10;
 20 	cout<<"默认值:"<<endl;
 21 	cout<<"a="<<a<<",b="<<b<<endl;
 22 	//第一种方法
 23 	tmp=a;
 24 	a=b;
 25 	b=tmp;
 26 	cout<<"第一种方法可行"<<endl;
 27 	cout<<"a="<<a<<",b="<<b<<endl;
 28 	a=5;b=10;//返回默认值
 29 
 30 	//第二种方法不行
 31 	swap(a,b);//传递参数的方式
 32 	cout<<"第二种方法不行"<<endl;
 33 	cout<<"a="<<a<<",b="<<b<<endl;
 34 
 35 	//第三种方法
 36 	swap1(&a,&b);
 37 	cout<<"第三种方法使用指针可以"<<endl;
 38 	cout<<"a="<<a<<",b="<<b<<endl;
 39 	a=5;b=10;//返回默认值
 40 
 41 	//第四种方法
 42 	SWAP2(a,b,tmp);
 43 	cout<<"第四种方法使用宏定义也可以"<<endl;
 44 	cout<<"a="<<a<<",b="<<b<<endl;
 45 	a=5;b=10;//返回默认值
 46 
 47 	//第五种方法
 48 	swap3(a,b);
 49 	cout<<"第五种方法:传引用"<<endl;
 50 	cout<<"a="<<a<<",b="<<b<<endl;
 51 	a=5;b=10;//返回默认值
 52 
 53 	//第六种方法
 54 	//使用封装好的C++函数
 55 	cout<<"第六种方法:使用std::swap函数"<<endl;
 56 	std::swap(a,b);
 57 	cout<<"a="<<a<<",b="<<b<<endl;
 58 	a=5;b=10;//返回默认值
 59 	system("pause");
 60 	return 0;
 61 }
 62 void swap(int x,int y)//这个方法不行
 63 {	//按值传递的方式传参数,相当于把a拷贝传给x,b拷贝传给y,原来的数并没有交换
 64 	int temp;
 65 	temp=x;
 66 	x=y;
 67 	y=temp;
 68 }
 69 void swap1(int *px,int *py)
 70 {
 71 	int temp;
 72 	temp=*px;
 73 	*px=*py;
 74 	*py=temp;
 75 }
 76 //引用就是别名
 77 void swap3(int &x,int &y)
 78 {
 79 	int temp;
 80 	temp=x;
 81 	x=y;
 82 	y=temp;
 83 }

VS2010中运行结果:

image

posted @ 2018-04-18 13:53  乱丶心  阅读(548)  评论(0)    收藏  举报