C ++中的布尔运算符NOR

时间:2019-04-08 17:39:21

标签: c++

我正在练习所有位的逻辑门实现,然后开始实现NOR,但我不知道为什么使用'〜'运算符会给出负值。当我使用'!'时,它确实给出了正确的结果。操作员。我无法找到我做错事背后的逻辑。

我通读了C ++中的运算符,并明确提到使用'〜'运算符和'!用于逻辑运算

void NOR(vector<string>& input){ // input is string of vectors with values 0 0, 0 1, 1 0, 1 1

cout<<"---------------------------------"<<endl;

  for(auto& i : input){

    cout<<"NOR of "<<i[0]<<" "<<i[1];

    cout<<" is "<<~((i[0]-'0') | (i[1]-'0'))<<endl;

  }

 cout<<"---------------------------------"<<endl;

}

我得到的结果是

NOR of 0 0 is -1

NOR of 1 0 is -2

NOR of 0 1 is -2

NOR of 1 1 is -2

1 个答案:

答案 0 :(得分:1)

C ++没有逻辑XOR运算符(只有按位XOR:^)。

对于NOR-C ++没有实现任何类型的NOR。

您可以简单地使用:

template <typename I>
constexpr I logical_nor(I lhs, I rhs) noexcept { return not (lhs or rhs); }

template <typename I>
constexpr I bitwise_nor(I lhs, I rhs) noexcept { return ~(lhs | rhs); }

,如果要将其应用于元素向量,则可以使用std::transformstd::for_each