首页 > 解决方案 > 如何创建具有唯一值的指针集

问题描述

假设我有一个定义如下的类

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不是一个选项。

标签: c++setunique

解决方案


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();
}

推荐阅读