我可以比较 C++ 中的 2 个结构吗?

jbs*_*u32 6 c++ structure

我只是简单地声明了一个这样的结构 -

struct data{
    int x,y;
};
Run Code Online (Sandbox Code Playgroud)

现在我宣布2个变量abdata类型。我已经为它们分配了适当的值。现在,我想检查它们是否相等!我正在尝试这样做 -

data a,b;
a.x=12, a.y=24;
b.x=15, b.y=30;
if(a!=b)cout<<"a~b"<<endl;
Run Code Online (Sandbox Code Playgroud)

但是编译器在线上给了我以下错误4th->

error: no match for 'operator!=' (operand types are 'data' and 'data')

其实问题出在哪里?C++ 不支持这个比较吗??还是我犯了什么错误??

做到这一点的确切和最简单的方法是什么?我是否需要分别比较结构中的每个元素?或者有其他更聪明的方法吗??

650*_*502 21

C++ 隐式地为您提供逐个属性的赋值,但不进行相等或排序的比较。原因是“只是因为”,不要太认真地研究哲学。

如果需要,您必须通过自己显式实现来提供这些运算符,例如:

bool operator<(const Data& other) const {
    if (x < other.x) return true;
    if (x > other.x) return false;
    return y < other.y;
}

bool operator==(const Data& other) const {
    return x == other.x && y == other.y;
}
Run Code Online (Sandbox Code Playgroud)

等等。

还要注意,例如定义不会自动==给你!=,定义<也不会>=隐式提供。

更新

C++20 引入(将引入)一个新的运算符<=>(友好名称“宇宙飞船运算符”),正是为了消除必须定义所有可能的关系运算符的冗长性。在这种情况下添加:

std::strong_ordering operator<=>(const Data& other) const {
    if (auto cmp = x <=> other.x; cmp != 0) return cmp;
    return y <=> other.y;
}
Run Code Online (Sandbox Code Playgroud)

将允许基于首先检查编译类元素之间的所有关系测试(<, <=, >, >=, ==, !=x,如果检查没有解决,则y改为检查。

  • `return std::tie(lhs.x, lhs.y) &lt; std::tie(rhs.x, rhs.y);` 非常方便,比手动方式更不容易出错。 (2认同)

nsh*_*hct 5

您必须明确实现您打算使用的所有运算符。在您的情况下,您需要提供bool operator!=(const data&, const data&).

为这样的 POD 实现它的一个好方法是使用std::tuple它,因为它已经实现了排序:

#include <tuple>

// ...

bool operator!=(const data& p_lhs, const data& p_rhs)
{
    return std::tie(p_lhs.x, p_lhs.y) != std::tie(p_rhs.x, p_rhs.y);
}
Run Code Online (Sandbox Code Playgroud)

std::tie(文档) 创建一个临时的引用元组。然后可以比较这两个元组,因为std::tuple定义了所有比较运算符,如下所示。

我选择实现operator!=为免费功能。当然,您可以选择将其作为类的成员来实现:

struct data
{
    bool operator!=(const data& p_rhs) const
    {
        return std::tie(x, y) != std::tie(p_rhs.x, p_rhs.y);
    }

    int x, y;
};
Run Code Online (Sandbox Code Playgroud)

当然,您也应该定义所有其他运算符。请记住,您可以通过委托给其他人来实现大多数运算符。