c++ - 如何创建具有唯一值的指针集
问题描述
假设我有一个定义如下的类
class Foo {
private:
int date;
std::string name;
public:
void setName(std::string a_name){ name = a_name; };
std::string getName(){ return name; };
void setDate(int a_date){ date = a_date; }
int getDate(){ return date; };
struct FooComparator
{
bool operator()(Foo* lhs, Foo* rhs) const { return lhs->getDate() < rhs->getDate(); }
};
}
现在我想创建几个对象Foo
并将它们放在按日期排序的集合中,所以我这样做
std::set<Foo *, Foo::FooComparator> entries;
Foo *a = new Foo();
a->setName("A_OBJ");
a->setDate(10);
entries.insert(a);
Foo *b = new Foo();
b->setName("B_OBJ");
a->setDate(1);
entries.insert(b);
Foo *a_2 = new Foo();
a_2->setName("A_OBJ");
a_2->setDate(9);
entries.insert(a_2);
所以这是问题所在,在我的集合中,我有 3 个条目排序,date
因为在指针值上检查了唯一性。有没有办法给set
自定义相等比较器,以便它不会插入a_2
,因为已经有一个具有该名称的条目?
我知道可以unordered_set
传递自定义哈希函数,但我似乎找不到类似的方法来做到这一点,set
因为我需要条目是唯一的并且排序unordered_set
不是一个选项。
解决方案
a
对于集合,和的相等性b
定义为!(a < b) && !(b < a)
。您应该更改比较器功能以反映:
bool operator()(Foo* lhs, Foo* rhs) const {
if (lhs->getName() == rhs->getName()) {
return false;
}
return lhs->getDate() < rhs->getDate();
}
推荐阅读
- flutter - Flutter:哪些 Material Widget 在 iOS 上运行?
- django - 自定义用户修改表单 django 管理站点
- vb.net - VB.net 从与其他 td 具有相同 ID/类的 td 获取文本
- javascript - 突出显示表 OnClick 中的列
- elasticsearch - 使用 Nest Client 将多语言 ElasticSearch 文档映射到单语言对象
- html - 仅在 CSS 中使用 %-width 覆盖图像高度 div
- flutter - 在 Flutter 中经过一段时间后隐藏小部件的简单方法
- java - Java中两个表的水平对齐
- python - 如何分解 3x3 矩阵
- python - 当我训练我的网络时,出现错误,预期目标大小 (4, 224),得到 torch.Size([4, 224, 224])