交换两个元素

来源:互联网 发布:java jdk1.8 32位 编辑:程序博客网 时间:2024/05/18 03:34

交换元素的代码一般有三种:

1.中间变量过渡。

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

2.减法运算。

template <class T> void Swap(T& a, T& b) {a = a - b;b = a + b;a = b - a;}

3.异或运算。

template <class T> void Swap(T& a, T& b) {if (&a == &b){return;}a ^= b ^= a ^= b;}

异或代码中有一个盲点:如果不加 &a == &b 的判断,那么,该函数不能交换同一个地址上的值,否则,会将a b置0。

这个需要记一下。

原创粉丝点击