低于结构体的操作符

Lower than operator for structs

本文关键字:操作符 结构体      更新时间:2023-10-16

我有一个包含两种数据类型的结构体,它们实现了小于、大于和等于操作符。我想为我的结构体实现小于操作符:

struct number_pair
{
    int a;
    int b;
    bool operator<(const pair& other) const { return ?; }
}

您需要能够使用操作符对结构体的多个实例进行排序。顺序应同时尊重ab。我不想使用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<

为了帮助理解底层概念,考虑比较两个文本字符串的一个更简单的例子。问问你自己,如何比较两个字符串?你应该知道答案:比较每个字符串的第一个字符。如果它们是相同的,继续到第二个字符,依此类推。我省略了处理长度不同的字符串的细节,但这是基本的基本概念。

这里的概念是完全相同的,如果你认为你总是有一个两个字符的字符串,并在心理上用ab替换这两个字符:

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::tupleboost::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);
    }
};