C++ 如何在不使用临时变量或算术运算的情况下交换两个数字?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3647331/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to swap two numbers without using temp variables or arithmetic operations?
提问by mr_eclair
This equation swaps two numbers without a temporary variable, but uses arithmetic operations:
这个等式交换两个没有临时变量的数字,但使用算术运算:
a = (a+b) - (b=a);
How can I do it without arithmetic operations? I was thinking about XOR.
如果没有算术运算,我该怎么做?我在考虑异或。
回答by sreejith k s
a=a+b;
b=a-b;
a=a-b;
This is simple yet effective....
这是简单而有效的......
回答by BiGYaN
回答by Martin York
Why not use the std libs?
为什么不使用标准库?
std::swap(a,b);
回答by Matthew Slattery
The best way to swap two numbers without using any temporary storage or arithmetic operations is to load both variables into registers, and then use the registers the other way around!
在不使用任何临时存储或算术运算的情况下交换两个数字的最佳方法是将两个变量加载到寄存器中,然后反过来使用寄存器!
You can't do that directly from C, but the compiler is probably quite capable of working it out for you (at least, if optimisation is enabled) - if you write simple, obvious code, such as that which KennyTM suggested in his comment.
你不能直接从 C 中做到这一点,但编译器可能完全有能力为你解决(至少,如果启用了优化)——如果你编写简单、明显的代码,比如 KennyTM 在他的评论中建议的代码.
e.g.
例如
void swap_tmp(unsigned int *p)
{
unsigned int tmp;
tmp = p[0];
p[0] = p[1];
p[1] = tmp;
}
compiled with gcc 4.3.2 with the -O2
optimisation flag gives:
使用带有-O2
优化标志的gcc 4.3.2 编译给出:
swap_tmp:
pushl %ebp ; (prologue)
movl %esp, %ebp ; (prologue)
movl 8(%ebp), %eax ; EAX = p
movl (%eax), %ecx ; ECX = p[0]
movl 4(%eax), %edx ; EDX = p[1]
movl %ecx, 4(%eax) ; p[1] = ECX
movl %edx, (%eax) ; p[0] = EDX
popl %ebp ; (epilogue)
ret ; (epilogue)
回答by Shubham A.
Using XOR,
使用异或,
void swap(int &a, int &b)
{
a = a ^ b;
b = a ^ b;
a = a ^ b;
}
One liner with XOR,
一个带有 XOR 的衬垫,
void swap(int &a, int &b)
{
a ^= b ^= a ^= b;
}
These methods appear to be clean, because they don't fail for any test-case, but again since (as in method 2) value of variable is modified twice within the same sequence point, it is said to be having undefined behavior declared by ANSI C.
这些方法看起来很干净,因为它们不会对任何测试用例失败,但同样因为(如方法 2 中)变量的值在同一序列点内被修改了两次,据说它具有声明的未定义行为ANSI C.
回答by Thomas Padron-McCarthy
I haven't seen this C solution before, but I'm sure someone has thought of it. And perhaps had more posting self-control than I do.
我以前没有见过这个 C 解决方案,但我相信有人已经想到了。也许比我有更多的发布自我控制。
fprintf(fopen("temp.txt", "w"), "%d", a);
a = b;
fscanf(fopen("temp.txt", "r"), "%d", &b);
No extra variables!
没有额外的变量!
It works for me, but depending on the stdio implementation you may have to do something about output buffering.
它对我有用,但根据 stdio 实现,您可能需要对输出缓冲做一些事情。
回答by Syed Raza Mehdi
a =((a = a + b) - (b = a - b));
回答by k06a
C++11
allows to:
C++11
允许:
std::swap(a, b);
std::swap_ranges(a.begin(), a.end(), b.begin());
std::tie(b, a) = std::make_tuple(a, b); std::tie(c, b, a) = std::make_tuple(a, b, c);
回答by Katie
In addition to the above solutions for a case where if one of the value is out of range for a signed integer, the two variables values can be swapped in this way
除了上述针对有符号整数的值之一超出范围的情况的解决方案之外,还可以通过这种方式交换两个变量的值
a = a+b;
b=b-(-a);
a=b-a;
b=-(b);
回答by Moiz Sajid
Multiplication and division can also be used.
也可以使用乘法和除法。
int x = 10, y = 5;
// Code to swap 'x' and 'y'
x = x * y; // x now becomes 50
y = x / y; // y becomes 10
x = x / y; // x becomes 5