我可以比较c++中的两种结构吗?

Can I compare 2 structures in C++?

本文关键字:结构 两种 比较 c++ 我可以      更新时间:2023-10-16

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

struct data{
    int x,y;
};

现在我已经声明了两个变量a &data型的b。我给它们赋了合适的值。现在,我想检查它们是否相等!我正试着这样做-

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

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

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

问题到底在哪里?c++中不支持这个比较吗??还是我犯了什么错误?

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

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;
}

等等

还请注意,例如定义==不会自动提供!=,定义<不会隐式提供>=

<标题> 更新

c++ 20引入了(将会引入)一个新的操作符<=>(友好的名字"spaceship operator"),正是为了消除必须定义所有可能的关系操作符的冗长性。在本例中添加:

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

将允许在先检查x的基础上编译类元素之间的所有关系测试(<, <=, >, >=, ==, !=),如果该检查不能解决,则检查y

您必须显式地实现您打算使用的所有操作符。在您的示例中,您需要提供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);
}

std::tie (documentation)创建一个临时的引用元组。然后可以比较这两个元组,因为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;
};

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

c++ 20中加入了自动比较,因此您只需添加一个特殊运算符来指示在新标准发布时需要默认比较。

class Point {
 int x;
 int y;
public:
 auto operator<=>(const Point&) const = default;
 // ... non-comparison functions ...
};
https://en.cppreference.com/w/cpp/language/default_comparisons

你必须实现bool operator != (const data&, const data&);

可能的实现(在c++11中):

#include <tuple>
//...
bool operator == (const data& lhs, const data& rhs) {
    return std::tie(lhs.x, lhs.y) == std::tie(rhs.x, rhs.y);
}
bool operator != (const data& lhs, const data& rhs) {
    return !(lhs == rhs);
}