It is very simple to implement an array inverse with an element exchange function, as in the following code: (array of left and right element Exchange)
#include <iostream> #include <stdlib.h>using namespace std;void swap (int &a, int &b) {int tmp = A;A = B;b = tmp;} int main () {int a[5] = {1, 2, 3, 4, 5};int lenth = sizeof (a)/sizeof (a[0]), int head = 0;int tail = lenth-1;while (head <= tail) {swap (A[head], a[tail]); head++;tail--;} for (int i = 0; i < lenth; ++i) {cout << a[i] << Endl;} System ("Pause");}
some would say that using XOR or operation to make the switching function more efficient , write the following code:
<span style= "font-family:kaiti_gb2312;" > #include <iostream> #include <stdlib.h>using namespace std;void swap (int &a, int &b) {a = a ^ B;b = a ^ B;a = a ^ b;} int main () {int a[5] = {1, 2, 3, 4, 5};int lenth = sizeof (a)/sizeof (a[0]), int head = 0;int tail = lenth-1;while (head <= tail) {swap (A[head], a[tail]); head++;tail--;} for (int i = 0; i < lenth; ++i) {cout << a[i] << Endl;} System ("Pause");} </span>
A run, the results of the surprise: 0 where????
the mechanism by which an XOR operation implements the interchange: a ^ a = 0 means that the same element is different or after 0
A = a ^ b;
b = a ^ b = a ^ b ^ b = A;
A = a ^ b = a ^ b ^ a = b;
After analysis: So, when head = Tail = (lenth-1)/2 o'clock, they point to the same element, i.e.
A = b = 3 (same piece of memory)
A = a ^ b = 3 ^ 3 = 0 (memory content changed to 0)---->>> A = b = 0;
b = a ^ b = 0 ^ 0 = 0
A = a ^ b = 0 ^ 0 = 0
So after execution, it becomes 0.
So how to modify it???
while (Head < tail)//change here {swap (A[head], a[tail]); head++;tail--;}
Note Later that the conditions are written while (Head < tail) that the same element does not need to be exchanged, that is, speed up the execution efficiency, but also avoid the above problems!!
A related question click Open link
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
An Exchange function implemented by XOR and operation to realize the problems needing attention in the inverse of array