Reverse 在C+中使用^=进行反转+;

Reverse 在C+中使用^=进行反转+;,reverse,xor,Reverse,Xor,我玩反弦游戏 std::string simpleReverse(std::string inputX) { //std::string inputX; std::cout << "Enter a word for revesrse" << std::endl; std::cout << "You have entered '" << inputX << "'...\nResult is:"; std::string resultA

我玩反弦游戏

std::string simpleReverse(std::string inputX) {
//std::string inputX;
std::cout << "Enter a word for revesrse" << std::endl;
std::cout << "You have entered '" << inputX << "'...\nResult is:";

std::string resultA = inputX;

for (int i=inputX.length()-1, j = 0; i>=0, j<5; i--, j++){
    //std::cout << inputX[i] << std::endl;
    resultA[j] = inputX[i];
}
inputX = resultA;
std::cout << resultA;
std::string simpleReverse(std::string inputX){
//std::字符串输入;

std::cout要交换两个值
a
b
,我们可以编写:

a = a ^ b;
b = a ^ b;
a = a ^ b;
有关更多信息,请参阅

这段代码就是这个算法,但只写了一行。首先:

a ^= b;
b ^= a;
a ^= b;
然后进一步压缩。请注意,
a^=b
返回新的
a
,它代替
b^=a
,使我们能够写入
b^=a^=b

^表示按位异或 它所做的是,它只在相同的位置保留那些位,而这两个变量的位是不同的

e、 g'a'=1000001
“b”=1000010
a^b将是0000011

现在你知道了不同的比特,当你知道两个“a”或“b”中的任何一个时,它会给你另一个作为结果

i、 e'a'=1000001
“a”^“b”=0000011
1000010//给你“b”

公共位将来自“a”,而“a”的不同位将更改为0,因此只剩下“b”的不同位。因此,将为您提供“b”

str[i]^=str[j]^=str[i]^=str[j];
要简化这一点:

str[i]^=str[j]; expands to str[i]=str[i]^str[j]; //'a'^'b'
下一步:

str[j]^=str[i]^=str[j]; expands to str[j]=('a'^'b')^'b'//str[j]=str[i] which is 'a' in our case
最后

str[i]^=str[j]^=str[i]^=str[j]; //'a'^('a'^'b')//str[i]=str[j] which is 'b' in our case
所以他们交换了


希望能有所帮助。

^
是按位异或运算符,可以组合起来交换值。虽然这样做有效,但这是一个糟糕的代码,因为它很难被人读取。其他选项,如
std::swap()
更可取。感谢解释,简单的解释是1+2=3,3-2=1,3-1=2;所以第一次交换似乎没有使用;是的,但是^是位运算符,所以它在位级别上执行所有操作。如果你阅读我的解释,你会发现它非常有趣:)你能给我一个这个运算符有用的例子吗?我很惊讶这个值可以被交换p与比特,将学习更多如何明智地使用它
str[i]^=str[j]^=str[i]^=str[j]; //'a'^('a'^'b')//str[i]=str[j] which is 'b' in our case