不使用tmp变量交换两个整数? [英] swap two integers without using a tmp variable?

查看:106
本文介绍了不使用tmp变量交换两个整数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在不使用tmp变量的情况下重写交换函数

交换函数????


int main()

{

int x = 3;

int y = 5;


//通过引用传递


cout<< 通过引用传递,之前 << endl;

cout<< x = << x<< " y =" << y<< endl;


swap(x,y);


cout<< 通过引用传递,之后 << endl;

cout<< x = << x<< " y =" << y<< endl;


返回0;

}


void swap(int& x,int& y )

{

int tmp;


tmp = x;

x = y;

y = tmp;

}

How do you rewrite the swap function without using a tmp variable in
the swap function????

int main()
{
int x = 3;
int y = 5;

// Passing by reference

cout << "Passed by reference, before" << endl;
cout << "x = " << x << " y = " << y << endl;

swap(x,y);

cout << "Passed by reference, after" << endl;
cout << "x = " << x << " y = " << y << endl;

return 0;
}

void swap(int &x, int &y)
{
int tmp;

tmp = x;
x = y;
y = tmp;
}

推荐答案

" Steve" <纳克***** @ my-deja.com>写道...
"Steve" <ng*****@my-deja.com> wrote...
如何在不使用交换函数的tmp变量的情况下重写交换函数????
How do you rewrite the swap function without using a tmp variable in
the swap function????




以前有一个流行的技巧,包括在
三步中对整数进行异或运算,这样你就可以避免定义一个临时的

存储,但它要少得多清楚而不是暂时的。


int a = 42,b = 73;

b = a ^ b;

a = b ^ a;

b = a ^ b;

//这里''''是73,''b''是42.

但是,最好依靠std :: swap来实现。


V



There used to be a popular trick involving XORing the integers in
three steps, which allowed you to avoid having to define a temporary
storage, but it is much less clear than with a temporary.

int a = 42, b = 73;
b = a ^ b;
a = b ^ a;
b = a ^ b;
// here ''a'' is 73, ''b'' is 42.

However, it''s better to rely on std::swap for that.

V


Steve 2004-06-22:
Steve 2004-06-22 :
如何在不使用交换函数的tmp变量的情况下重写交换函数????
How do you rewrite the swap function without using a tmp variable in
the swap function????



通过做一些可以被称为交叉xoring的东西,与运营商^ =

我把它留作练习,因为它很有趣:-)

(不要担心tmp:记住自动变量可以存在于
寄存器中)


Walter Tross



By doing something which could be called cross-xoring, with operator ^=
I leave it as an exercise, since it is fun :-)
(Don''t worry about the tmp: remember that auto variables can live in
registers)

Walter Tross


2004年6月22日星期二00:15:43 GMT,Victor Bazarov< v。******** @ comAcast.net>写道:
On Tue, 22 Jun 2004 00:15:43 GMT, Victor Bazarov <v.********@comAcast.net> wrote:
曾经有过一个流行的技巧,涉及对三个步骤进行整数异或,这样就可以避免定义一个临时的存储,但是它比临时的要清楚得多。

int a = 42,b = 73;
b = a ^ b;
a = b ^ a;
b = a ^ b;
//这里''''是73,''b''是42。
There used to be a popular trick involving XORing the integers in
three steps, which allowed you to avoid having to define a temporary
storage, but it is much less clear than with a temporary.

int a = 42, b = 73;
b = a ^ b;
a = b ^ a;
b = a ^ b;
// here ''a'' is 73, ''b'' is 42.




或者可以使用定期加法和结构:


b = a + b;

a = b - a;

b = b - a;


-

Maxim Yegorushkin



Or one can use regular addition and substruction:

b = a + b;
a = b - a;
b = b - a;

--
Maxim Yegorushkin


这篇关于不使用tmp变量交换两个整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆