集合元素类中定义的集合的比较器
Comparator for set defined in the class of the set elements
我有一个类,指向该类对象的指针需要放在std::set
中。我想在类中定义比较器。我见过一些解决方案,其中要么定义了一个单独的类(我想它被称为函子),要么定义了重载operator()
的结构。我希望避免使用这种样板代码,并希望将比较器定义为类本身的一个成员,类似于Java的compareTo()
方法。
比方说,我的课是这样的:
class Item {
private:
int id;
float score;
.....
public:
// Rest of the methods and setters/getters
}
我想定义比较器的方式是,指向得分较高的对象的指针放在集合的第一位。如果两者的得分相等,则id较低的一个将被放在第一位。我想代码会是如下所示,但由于我不太理解这一部分,请纠正我(我希望将其放在类中):
bool operator()(const Item* a, const Item* b) {
if (a->score != b->score) return a->score > b->score;
return a->id < b->id;
}
用法如下:
std::set<Item*> sortedItems;
Item* item = new Item();
sortedItems.insert(item);
如果在类中定义,我不确定是否需要在std::set
模板中指定比较器,如果需要,如何指定?此外,如何在类本身中添加此比较器?我是STL的新手,也是C++的新手。谢谢
这个解决方案的灵感来自这个答案。
#include <set>
class Item {
private:
int id;
float score;
public:
struct compare {
bool operator()(const Item* a, const Item* b) {
if (a->score != b->score) return a->score > b->score;
return a->id < b->id;
}
};
};
因为set允许您定义自己的比较方法,所以可以按如下方式使用它。
std::set<Item*, Item::compare> sortedItems;
这应该允许你的类项目与设置一起工作
set<T>
实现想要调用a < b
,其中a
和b
是类型为T
的对象。只要该调用有效,集合就不在乎;它可以是采用一个参数的非静态成员函数、采用两个参数的静态成员函数或采用两个变量的自由函数:
class Item {
public:
bool operator<(const Item& rhs) {
return score == rhs.score ? id < rhs.id : score < rhs.score;
}
static bool operator<(const Iterm& lhs, const Item& rhs) {
return lhs.score == rhs.score ? lhs.id < rhs.id : lhs.score < rhs.score;
}
};
bool operator<(const Item& lhs, const Item& rhs) {
return lhs.score == rhs.score ? lhs.id < rhs.id : lhs.score < rhs.score;
}
这三个人中的任何一个都可以。当然,如果你写了两个或两个以上,你会有歧义。
相关文章:
- std::设置自定义比较器
- C++中"std::sort"比较器的不同类型
- 将 std::set 与基于键的比较器一起使用
- 带自定义比较器的最小优先级队列
- 函数类作为比较器
- 优先级队列自定义比较器
- 什么是自定义比较器以及如何在 C++ 的排序函数中使用它?
- 没有默认构造函数作为模板参数的自定义比较器
- set_intersection使用自定义设置比较器
- 如何为集合 c++ 建立比较器
- C++复杂情况的比较器通过参数问题
- 对于BTreeMap和其他依赖于Ord的东西,是否有等效于C++比较器对象?
- 对没有比较器或λ函数的向量进行排序?
- 集合比较器的正向声明
- 集合元素类中定义的集合的比较器
- 自定义比较器,将唯一元素插入到c++中的集合中
- 用C++中的比较器初始化集合
- C2100非法间接比较器和集合
- 具有透明比较器和异构意义上的非唯一元素的映射或集合
- 从集合<A*,比较器>中获取A成员以列出<A>