是否可以为通用元素列表创建排序

Is it possible to create an ordering for a list of generic elements?

本文关键字:元素 列表 创建 排序 是否      更新时间:2023-10-16

是否可以创建一个函数,该函数接受任何可以想象的类型的元素列表,并返回一个可以作为排序元素的比较器的运算符?换句话说,

template typename<T> ??? getComparator ( T a )
{
     // ...
}

我把???放在哪里,因为我不确定返回类型是什么。然而,我的想法是,如果我调用

getComparator(int i)

它可能会返回

bool smallerThan(int a, int b) { return (a < b); }

如果我创建了一个自定义对象

struct thingamabob { int i; std::string s; int ***** ptr; }
thingamabob myThing; 

我可以将myThing馈送到getComparator中,它将找出如何创建返回类型bool的函数,该函数接受两个类型myThing的对象,并且对于任何3个对象

thingamabob thing1, thing2, thing3; 

带有

thing1 != thing2 && thing2 != thing3 && thing1 != thing3

那么我可以得到一些<,这样

thing1 <= thing2 && thing2 <= thing3

thing1 <= thing3 && thing3 <= thing2

thing3 <= thing1 && thing1 <= thing2

thing2 <= thing1 && thing1 <= thing3

thing2 <= thing3 && thing3 <= thing1

thing3 <= thing1 && thing1 <= thing2

thing3 <= thing2 && thing2 <= thing3

我很确定您正在寻找std::less<T>:这是一个函数对象,它将比较两个类型为T的对象。

然而,它需要定义operator<——这对int来说很好,但对thingamabob来说——你必须自己编写这个运算符。编译器如何知道你说一个thingamabob小于另一个的意思,除非你告诉它?

C++中没有这样的功能(截至2015年,因此包括C++14之前的所有标准(。然而,Bjarne Stroustrup已经编写了一份建议,将默认的比较运算符添加到标准中。

这本质上是为您生成一个比较运算符,以防您自己没有声明这些运算符。它只是对类/结构的数据成员进行字典排序。然而,到目前为止,这还没有在任何主流编译器中实现,也不确定它是否会被添加到官方C++标准中。你必须坚持自己去实现它。

该提案定义了一些不会生成默认比较运算符的情况,例如,如果存在指针成员。这是因为这样的比较可能很容易调用未定义的行为。

做到这一点的直接代码是:

bool operator<(const Type& first, const Type& second)
{
    return std::tie(first.member1,  first.member2) <
           std::tie(second.member1, second.member2);
}
bool operator>=(const Type& first, const Type& second)
{
   return !(first < second);
}
bool operator>(const Type& first, const Type& second)
{
   return second < first;
}
bool operator<=(const Type& first, const Type& second)
{
   return !(first > second);
}