繁体   English   中英

C ++中的逻辑异或运算符?

[英]Logical XOR operator in C++?

有这样的事情吗? 这是我第一次遇到实际需求,但我没有看到Stroustrup 中列出 的需求 我打算写:

// Detect when exactly one of A,B is equal to five.
return (A==5) ^^ (B==5);

但是没有^^运算符。 我可以在这里使用按位^并得到正确答案(无论真假的机器表示如何)? 我从不混合&&& ,或| || ,所以我犹豫要不要使用^^^

我会更舒服地编写自己的bool XOR(bool,bool)函数。

!=运算符用于bool值。

对于真正的逻辑异或运算,这将起作用:

if(!A != !B) {
    // code here
}

注意! 在那里将值转换为布尔值并否定它们,以便两个不相等的正整数(每个都是true )评估为false

正确的手动逻辑XOR 实现取决于您想用 XOR 模拟其他逻辑运算符( ||&& )的一般行为的程度。 关于这些运算符有两个重要的事情:1)它们保证短路评估,2)它们引入了一个序列点,3)它们只评估它们的操作数一次。

如您所知,XOR 评估不能短路,因为结果始终取决于两个操作数。 所以1是没有问题的。 但是2呢? 如果您不关心 2,那么使用规范化(即bool )值运算符!=就结果而言执行 XOR 的工作。 操作数可以很容易地用一元归一化! ,如有必要。 因此!A != !B在这方面实现了正确的 XOR。

但是,如果您关心额外的序列点,则!=和按位^都不是实现 XOR 的正确方法。 正确执行 XOR(a, b) 的一种可能方法可能如下所示

a ? !b : b

这实际上与制作与|| “相似”的自制 XOR 非常接近&& 当然,这只有在您将 XOR 实现为宏时才有效。 函数不会这样做,因为排序不适用于函数的参数。

有人可能会说,在每个&&||处都有一个序列点的唯一原因是为了支持短路评估,因此 XOR 不需要一个。 这实际上是有道理的。 然而,值得考虑在中间有一个序列点的异或。 例如,下面的表达式

++x > 1 && x < 5

在 C/C++ 中定义了行为和特定结果(至少在排序方面)。 因此,人们可能会合理地期望用户定义的逻辑XOR 会得到相同的结果,如

XOR(++x > 1, x < 5)

而基于!=的 XOR 没有这个属性。

还有另一种方式进行异或:

bool XOR(bool a, bool b)
{
    return (a + b) % 2;
}

显然可以通过以下方式证明可以工作:

#include <iostream>

bool XOR(bool a, bool b)
{
    return (a + b) % 2;
}

int main()
{
    using namespace std;
    cout << "XOR(true, true):\t" << XOR(true, true) << endl
         << "XOR(true, false):\t" << XOR(true, false) << endl
         << "XOR(false, true):\t" << XOR(false, true) << endl
         << "XOR(false, false):\t" << XOR(false, false) << endl
         << "XOR(0, 0):\t\t" << XOR(0, 0) << endl
         << "XOR(1, 0):\t\t" << XOR(1, 0) << endl
         << "XOR(5, 0):\t\t" << XOR(5, 0) << endl
         << "XOR(20, 0):\t\t" << XOR(20, 0) << endl
         << "XOR(6, 6):\t\t" << XOR(5, 5) << endl
         << "XOR(5, 6):\t\t" << XOR(5, 6) << endl
         << "XOR(1, 1):\t\t" << XOR(1, 1) << endl;
    return 0;
}

XOR 运算符不能短路; 即您不能仅通过评估其左手操作数来预测 XOR 表达式的结果。 因此,没有理由提供^^版本。

发布了一些很好的代码,比 !a != !b 更好地解决了问题

请注意,我必须添加 BOOL_DETAIL_OPEN/CLOSE 以便它适用于 MSVC 2010

/* From: http://groups.google.com/group/comp.std.c++/msg/2ff60fa87e8b6aeb

   Proposed code    left-to-right?  sequence point?  bool args?  bool result?  ICE result?  Singular 'b'?
   --------------   --------------  ---------------  ---------- ------------  -----------  -------------
   a ^ b                  no              no             no          no           yes          yes
   a != b                 no              no             no          no           yes          yes
   (!a)!=(!b)             no              no             no          no           yes          yes
   my_xor_func(a,b)       no              no             yes         yes          no           yes
   a ? !b : b             yes             yes            no          no           yes          no
   a ? !b : !!b           yes             yes            no          no           yes          no
   [* see below]          yes             yes            yes         yes          yes          no
   (( a bool_xor b ))     yes             yes            yes         yes          yes          yes

   [* = a ? !static_cast<bool>(b) : static_cast<bool>(b)]

   But what is this funny "(( a bool_xor b ))"? Well, you can create some
   macros that allow you such a strange syntax. Note that the
   double-brackets are part of the syntax and cannot be removed! The set of
   three macros (plus two internal helper macros) also provides bool_and
   and bool_or. That given, what is it good for? We have && and || already,
   why do we need such a stupid syntax? Well, && and || can't guarantee
   that the arguments are converted to bool and that you get a bool result.
     Think "operator overloads". Here's how the macros look like:

   Note: BOOL_DETAIL_OPEN/CLOSE added to make it work on MSVC 2010
  */

#define BOOL_DETAIL_AND_HELPER(x) static_cast<bool>(x):false
#define BOOL_DETAIL_XOR_HELPER(x) !static_cast<bool>(x):static_cast<bool>(x)

#define BOOL_DETAIL_OPEN (
#define BOOL_DETAIL_CLOSE )

#define bool_and BOOL_DETAIL_CLOSE ? BOOL_DETAIL_AND_HELPER BOOL_DETAIL_OPEN
#define bool_or BOOL_DETAIL_CLOSE ? true:static_cast<bool> BOOL_DETAIL_OPEN
#define bool_xor BOOL_DETAIL_CLOSE ? BOOL_DETAIL_XOR_HELPER BOOL_DETAIL_OPEN

使用一个简单的:

return ((op1 ? 1 : 0) ^ (op2 ? 1 : 0));

以下是我认为您在 C++ 中编写 XOR 比较的方式:

bool a = true;   // Test by changing to true or false
bool b = false;  // Test by changing to true or false
if (a == !b)     // THIS IS YOUR XOR comparison
{
    // do whatever
}

证明

XOR TABLE
 a   b  XOR
--- --- ---
 T   T   F
 T   F   T
 F   T   T
 F   F   F

a == !b TABLE
 a   b  !b  a == !b
--- --- --- -------
 T   T   F     F
 T   F   T     T
 F   T   F     T
 F   F   T     F

证据是对输入和输出的详尽研究表明,在两个表中,对于每个输入集,两个表中的结果始终相同。

因此,最初的问题是如何写:

return (A==5) ^^ (B==5)

答案是

return (A==5) == !(B==5);

或者如果你喜欢,写

return !(A==5) == (B==5);

(A || B) && !(A && B)

第一部分是A OR B,即Inclusive OR; 第二部分是,NOT A AND B。你一起得到 A 或 B,但不能同时得到 A 和 B。

这将提供在下面的真值表中证明的异或。

|-----|-----|-----------|
|  A  |  B  |  A XOR B  |
|-----|-----|-----------|
|  T  |  T  |   False   |
|-----|-----|-----------|
|  T  |  F  |   True    |
|-----|-----|-----------|
|  F  |  T  |   True    |
|-----|-----|-----------|
|  F  |  F  |   False   |
|-----|-----|-----------|

我使用“xor”(它似乎是一个关键字;在Code::Blocks中至少它变得粗体)就像您可以使用“and”代替&&和“or”代替|| .

if (first xor second)...

是的,它是按位的。 对不起。

#if defined(__OBJC__)
    #define __bool BOOL
    #include <stdbool.h>
    #define __bool bool
#endif

static inline __bool xor(__bool a, __bool b)
{
    return (!a && b) || (a && !b);
}

它按定义工作。 条件是检测您是否使用Objective-C ,它要求 BOOL 而不是 bool (长度不同!)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM