错误:“操作员^”无匹配



如何在字符串中进行刻度XOR?任何人都可以帮我吗?

#include <bits/stdc++.h>
using namespace std;
int main() {
    // your code goes here
    string a="1001";
    string b="1111";
    string c=a^b;
    cout << "c: " << c << "n";
    return 0;
}

错误:"操作员^'无匹配(操作数类型为'std :: __ cxx11 :: string {aka std :: __ __ cxx11 :: basic_string}'and std :: __ cxx11 :: string:: basic_string}') 字符串C = a^b;

考虑使用std :: bitset,这可能是您要寻找的。

std::bitset<4> a("1001");
std::bitset<4> b("1111");
std::bitset<4> c = a ^ b;
cout << "c: " << c << "n";

在IDEONE中看到它

可以从您的位字符串初始化它们,并具有operator^重载以进行XOR操作。还有一个Ostream&amp;操作员&lt;&lt;(ostream&amp;,const bitset <N>&amp;)用于打印结果std::cout

如何在字符串中进行刻度XOR?

位运算符只能与积分类型一起使用。

您必须从字符串中提取数字,将它们转换为积分类型,对其进行位于位置操作,然后从它们创建一个新字符串。

string a="1001";
string b="1111";
string c;
// With all the details spelled out.
for ( int i = 0; i < 4; ++i )
{
    char ac = a[i];
    char bc = b[i];
    // You should not use ac ^ bc even though char is an
    // integral type because the ^ will be performed on the
    // integral value used to encode the character.
    // Hence, you need to convert the char '0' to the number 0.
    int ai = ac - '0';
    int bi = bc - '0';
    int ci = ai ^ bi;
    char cc = ci + '0';
    c += cc;
}
// with all the details inlined
for ( int i = 0; i < 4; ++i )
{
    c += ((a[i] - '0') ^ (b[i] - '0')) + '0';
}

我认为您的意思是使用二进制字段而不是字符字符串。如果您想使用二进制文字,请查看这篇文章。

您可能想这样做:

int getBit(int n, int k)
{
    return (n & (1<<k)) != 0;
}
int main() 
{
  int a = 0b1001;
  int b = 0b1111;
  int c = a^b;
  for(int i = 3; i >= 0; i++)
       cout << getBit(c, i);
  return 0;
}

最新更新