是否可以为通用元素列表创建排序
Is it possible to create an ordering for a list of generic elements?
是否可以创建一个函数,该函数接受任何可以想象的类型的元素列表,并返回一个可以作为排序元素的比较器的运算符?换句话说,
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);
}
相关文章:
- C++如何通过用户输入删除列表元素
- 访问类lintalizer列表中的结构元素
- 从嵌套在std::映射中的std::列表中删除元素的最佳方式
- 删除列表中的第n个元素
- 从C++中的对列表中访问特定元素
- 访问动态分配列表中的元素
- 如何在 c++ 中根据第二个元素按降序对列表进行排序
- 如何在 c++ stl 中获取列表中被推回的元素的地址,在常量时间内?
- 删除列表 c++ 中的最后 3 个元素
- C++:带有大括号初始化列表的函数调用表达式 - 标准是否规定在单个元素列表的微不足道的情况下忽略大括号?
- 有什么方法可以将元素添加到列表中,如图所示?
- 动态分配列表 - 创建一个函数,用于删除所有包含偶数值的元素
- 如何通过保持第一个插入的位置来对列表中插入的其余元素进行排序?
- 如何使用cpp编写选择排序算法以降序对元素列表进行排序?
- (C++)如何创建一个函数来接收两个排序的链表并返回出现在两个列表中的第三个元素列表
- 刷新元素列表视图 QML
- SQLite:通过100K元素列表选择IN
- 解析字符串以创建元素列表
- 向vector添加可变大小元素列表的语法糖
- 是否可以为通用元素列表创建排序