您的位置:首页 > 编程语言 > C语言/C++

C++交换两个数总结

2016-03-26 00:26 555 查看
习题:实现两个整数的交换。

方法1:设置中间变量

#include<iostream>
using namespace std;
int main()
{
int a,b,c;
cout<<"Please input two numbers:"<<endl;
cin>>a>>b;
c = a;
a = b;
b = c;

cout<<"After changing:"<<endl;
cout<<a<<" "<<b<<endl;

system("pause");
return 0;
}


方法2:直接交换,不利用中间变量:

#include<iostream>
using namespace std;
int main()
{
int a,b;
cout<<"Please input two numbers:"<<endl;
cin>>a>>b;
a = a + b;         //但是加法可能会最终导致溢出
b = a - b;
a = a - b;

cout<<"After changing:"<<endl;
cout<<a<<" "<<b<<endl;

system("pause");
return 0;
}


或者采用“异或”:

#include<iostream>
using namespace std;
int main()
{
int a,b;
cout<<"Please input two numbers:"<<endl;
cin>>a>>b;
a = a^b;
b = a^b;
a = a^b;
// b ^= a ^= b ^= a; // 可以简写

cout<<"After changing:"<<endl;
cout<<a<<" "<<b<<endl;

system("pause");
return 0;
}


方法3:在C++中支持模板操作,所以可以利用这个写一个通用的change操作:

#include<iostream>
using namespace std;

template <class T>
void change(T &a,T &b)
{
T ch;
ch = a;
a = b;
b = ch;
}

int main()
{
int a,b;
cout<<"Please input two numbers:"<<endl;
cin>>a>>b;
change(a,b);

cout<<"After changing:"<<endl;
cout<<a<<" "<<b<<endl;

system("pause");
return 0;
}


方法4:采用指针:

#include<iostream>
using namespace std;

void change(int *p, int *q)
{
int ch;
ch = *p;
*p = *q;
*q = ch;
}

int main()
{
int a,b;
int *p1,*p2;
cout<<"Please input two numbers:"<<endl;
cin>>a>>b;
p1 = &a;
p2 = &b;

change(p1,p2);
cout<<"After changing:"<<endl;
cout<<*p1<<" "<<*p2<<endl;

system("pause");
return 0;
}


方法5:采用“引用”:

#include<iostream>
using namespace std;

void change(int& a,int &b)
{
int tmp;
tmp=a;
a=b;
b=tmp;
}
int main()
{
int a,b;
cout<<"Please input two numbers:"<<endl;
cin>>a>>b;
change(a,b);

cout<<"After changing:"<<endl;
cout<<a<<" "<<b<<endl;

system("pause");
return 0;
}


方法6:采用指针,并且不用临时变量:

#include<iostream>
using namespace std;

void change(int *a, int *b)
{
*a = *a + *b;    //这里同理也可以换成“异或”
*b = *a - *b;
*a = *a - *b;
}
int main()
{
int a,b;
cout<<"Please input two numbers:"<<endl;
cin>>a>>b;
change(&a,&b);

cout<<"After changing:"<<endl;
cout<<a<<" "<<b<<endl;

system("pause");
return 0;
}


方法7:采用汇编的方法进行交换:

#include<iostream>
using namespace std;

int main()
{
int a,b;
cout<<"Please input two numbers:"<<endl;
cin>>a>>b;

_asm
{
push a;
push b;
pop a;
pop b;
};

cout<<"After changing:"<<endl;
cout<<a<<" "<<b<<endl;

system("pause");
return 0;
}


扩展:不使用临时变量交换N个整型数的操作,即有N(N>=2)个变量,不使用临时变量,如何顺次交换它们的值?

具体答案可以参考资料2和资料4。

总结:以上总结了C/C++中交换两个数的一些方法。另外,swap()这个其实是C++标准模板库中函数,该函数可以交换任意两个类型。除此之外,在标准C++中string,vector,map,set等容器都是有swap函数的。详细介绍见参考资料2。

参考资料:

1、C语言实现交换两个数

2、交换两个整型数的方法

3、交换两个整数的三种实现方法(C/C++)

4、不用临时变量交换两个数的值
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C++