#define swap(a,b) a^=b^=a^=b的问题 | 交换宏的错误
程序员文章站
2022-03-22 08:27:59
#include//#includeusing namespace std;const int N = 1000000;int a[N];int n;void swap(int &a,int &b){printf("a = %d, b = %d",a,b);a^=b^=a^=b;printf("-> a = %d, b = %d\n",a,b);}void qs(int l,int r){....
#include<stdio.h>
//#include<algorithm>
using namespace std;
const int N = 1000000;
int a[N];
int n;
void swap(int &a,int &b){
printf("a = %d, b = %d",a,b);
a^=b^=a^=b;
printf("-> a = %d, b = %d\n",a,b);
}
void qs(int l,int r){
if(l>=r)return;
swap(a[l],a[(l+r)/2]);
int i = l,j = r;
int p = a[l];
while(i<j){
while(i<j&&a[j]>=p)j--;
while(i<j&&a[i]<=p)i++;
swap(a[i],a[j]);
}
swap(a[l],a[j]);
qs(l,i);
qs(i+1,r);
}
int main(){
scanf("%d",&n);
for(int i =0;i<n;i++)scanf("%d",&a[i]);
qs(0,n-1);
for(int i = 0;i<n;i++)printf("%d ",a[i]);
}
在这段快排代码中
void swap(int &a,int &b){
printf("a = %d, b = %d",a,b);
a^=b^=a^=b;
printf("-> a = %d, b = %d\n",a,b);
}
这个操作显然没有得到正确的结果
但是单独运行却是正常的
在异或运算当中
printf("a = %d, b = %d",a,b);
a^=b^=a^=b;
printf("-> a = %d, b = %d\n",a,b);
printf("a = %d, a = %d",a,a);
a^=a^=a^=a;
printf("-> a = %d, a = %d\n",a,a);
偶数次疑异或将会得到0
参考:利用异或解题
本文地址:https://blog.csdn.net/ZXYhappiness/article/details/107283269
上一篇: 编译hi3516a SDK遇到的问题