我可以比较c++中的两种结构吗?
Can I compare 2 structures in C++?
我简单地声明了一个这样的结构-
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&)
。
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);
}
- 在C++中将函数压缩为两种方式
- 如何使映射键具有两种不同的数据类型?
- 两种访问I2C总线的方法有什么区别?
- 两种模板示例有什么区别?
- 如何构造可以调用和返回两种不同类型的模板
- 这两种C++语法之间有什么区别?
- 为什么两种不同的对象初始化方式给出不同的输出
- std::cin 从控制台获取两种不同的变量类型,'storing'以后使用第二种类型?
- 定义类模板构造函数的两种方法之间的区别
- 初始化类的两种方法?
- C++ 一个函数,可以根据接受的值返回两种类型之一
- 如何使用指针连接两种不同的节点类型(结构)?
- 尝试连接两种不同类型的结构来创建链表
- 初始化结构的两种方式
- 动态分配一维结构数组:两种方法
- 这两种类型的结构的写法是一样的吗?
- 模板结构可容纳两种类型,但当时只有一种
- 使 NetBeans 针对两种体系结构进行构建
- 将数据从两种不同的数据结构插入 std::map <std::string, int> mymap 并通过套接字发送
- 我可以比较c++中的两种结构吗?