#include<iostream>
using namespace std;
void swap1(int &x, int &y){
x=x+y;
y=x-y;
x=x-y;
}
void swap2(int &x, int &y){
x=x*y;
y=x/y;
x=x/y;
}
//以上的加减以及乘除容易造成内存越界
void swap3(int &x, int &y){
//这里运用了异或的交换性:x^y^y=x^(y^y)=x^0=x
x=x^y;
y=x^y;
x=x^y;
}
//异或方法效率最高
int main(){
int x=1, y=2;
swap1(x, y);
cout<<x<<' '<<y<<endl;
swap2(x, y);
cout<<x<<' '<<y<<endl;
swap3(x, y);
cout<<x<<' '<<y<<endl;
}
无中间变量swap的三种方法
最新推荐文章于 2021-05-12 10:34:10 发布