交换变量没有辅助。无功... [英] exchange variables without aux. var...

查看:57
本文介绍了交换变量没有辅助。无功...的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,


我如何使用辅助值来交换两个整数变量的值而不用




= - =

kotee


9BF6 00E9 0CA9 B3A8 5234 03DB 3FB3 F85B 0033 74D7
http://keyserver.noreply.org/pks /loo...fingerprint=on

Hi all,

How can I exchange the values of two integer variable without
using an auxiliary one.

=--=
kotee


9BF6 00E9 0CA9 B3A8 5234 03DB 3FB3 F85B 0033 74D7
http://keyserver.noreply.org/pks/loo...fingerprint=on

推荐答案

" Szabolcs Szucs" < ko *** @ elte.huwrote in message

news:s7 ************* @ login08.caesar.elte.hu ...
"Szabolcs Szucs" <ko***@elte.huwrote in message
news:s7*************@login08.caesar.elte.hu...

大家好,


如何使用辅助设备交换两个整数变量的值而不用

一。
Hi all,

How can I exchange the values of two integer variable without
using an auxiliary one.



std :: swap(Int1,Int2);


虽然我确定std :: swap是一个复制本身,你不必。

std::swap( Int1, Int2 );

Although I''m sure std::swap makes a copy itself, you don''t have to.


Szabolcs Szucs写道:
Szabolcs Szucs wrote:

大家好,


如何使用辅助值交换两个整数变量的值而不用


Hi all,

How can I exchange the values of two integer variable without
using an auxiliary one.



有一种方法可以做到这一点,但它确实没有任何优势,所以不要b / b
麻烦。

There is a way to do it, but it doesn''t really have any advantage, so don''t
bother.


如何在没有
的情况下交换两个整数变量的值
How can I exchange the values of two integer variable without

使用辅助值。
using an auxiliary one.



假设你有变量:


int a = A,b = B;

并且想要在不使用辅助变量的情况下交换它们的值。

然后编写如下代码:


a + = b; //这给你一个==(A)+ B

b = a-b; //这给你b ==(A + B)-B == A

a - = b; //这给你一个==(A + B)-A == B


并完成!


但是如果这不是一个学校的任务然后这个方法不值得。

使用


std :: swap(a,b);


(正如Jim Langston所说)更好。一些处理器(用于

示例Pentium)支持交换寄存器或

内存值的指令 - 以及交换指令。可以用这个优势来实现。


Adam Badura

Lets say you have variables:

int a = A, b = B;

and want to exchange their values without using auxiliary variable.
Then write code like this:

a += b; // This gives you a == (A)+B
b = a-b; // This gives you b == (A+B)-B == A
a -= b; // This gives you a == (A+B)-A == B

and done!

However if this is not a school task then the method is not worth.
Using

std::swap(a, b);

(as Jim Langston sugested) is much better. Some processors (for
example Pentium) support instructions for exchanging registers or
memory values - and "swap" could be implemented using this advantage.

Adam Badura


这篇关于交换变量没有辅助。无功...的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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