低于结构体的操作符
Lower than operator for structs
我有一个包含两种数据类型的结构体,它们实现了小于、大于和等于操作符。我想为我的结构体实现小于操作符:
struct number_pair
{
int a;
int b;
bool operator<(const pair& other) const { return ?; }
}
您需要能够使用操作符对结构体的多个实例进行排序。顺序应同时尊重a
和b
。我不想使用std
以外的库,我在c++ 98上,所以std::tuple
不可用。
是否有可能实现我想要的,如果这两个数据类型只有小于,大于和等于操作符实现?如果是这种情况,操作符的实现看起来会是什么样子,否则,您还需要了解实现操作符的数据类型吗?
需要按字典顺序进行比较。这里有一个c++函数:std::lexicographical_compare
。此算法与用于排序std::tuple
对象的算法相同。
你可以很容易地自己实现这个(没有std::lexicographical_compare
),像这样:
struct pair {
int a;
int b;
bool operator<(const pair& other) const {
return a < other.a || (a == other.a && b < other.b);
}
};
或者,您可以使用std::pair<int, int>
来完成此操作。它已经定义了按字典顺序排列的operator<
为了帮助理解底层概念,考虑比较两个文本字符串的一个更简单的例子。问问你自己,如何比较两个字符串?你应该知道答案:比较每个字符串的第一个字符。如果它们是相同的,继续到第二个字符,依此类推。我省略了处理长度不同的字符串的细节,但这是基本的基本概念。
这里的概念是完全相同的,如果你认为你总是有一个两个字符的字符串,并在心理上用a
和b
替换这两个字符:
bool operator<(const pair& other) const {
if (a != other.a)
return a < other.a
return b < other.b;
}
对于这个简单的用例,这就足够了。在处理模板和其他复杂类型时,由于各种原因,通常只能使用<
操作符。如果您对自己施加同样的人为限制,仅根据<
本身实现自定义operator<
,则:
bool operator<(const pair& other) const {
if (a < other.a)
return true;
if (other.a < a)
return false;
return b < other.b;
}
虽然std::tuple
可能不可用,但您仍然可以使用boost::tuple
和boost::tie
:
#include <boost/tuple/tuple.hpp>
#include <boost/tuple/tuple_comparison.hpp>
struct number_pair
{
int a;
int b;
bool operator<(const number_pair& other) const {
return boost::tie(a, b) < boost::tie(other.a, other.b);
}
};
- 根据用户回答声明"Players"。用户选择玩家数量。播放器是结构体
- 结构体 S { int align; } 之间的区别;(struct 关键字后的名称)和 struct { int al
- C++ - 如何在结构向量中找到结构体一个成员的最大值?
- 包含 std::list 的结构体的 C++ 初始化
- 结构体和类的不同大小(),彼此具有相同的字段类型
- 如何使用结构体的向量数组?
- 如何使用结构体在C++中更改这些代码?
- 无法在 Mosquitto MQTT Broker 插件上访问结构体 mosquitto 的元素
- 我应该如何在C++中使用结构体解决输入失败的问题?
- Qsort() 比较结构体整数的总和
- 如何使用迭代器指向结构体c++的向量
- 在C++中使用链表的堆栈实现中,访问结构体headNode成员count和top会导致运行时错误
- 从结构体访问数据时,操作符重载到哪里去了?
- 返回指向类定义的结构体的指针,多个作用域操作符
- 低于结构体的操作符
- 定义操作符<为另一个结构体的两个对象在结构体中
- 将结构体的操作符重载为映射键
- 检查结构体是否为NULL或未设置,即使它的有操作符相等
- c++测试验证相等操作符随时间保持与结构体一致
- c++中所有操作符都可以在结构体中定义