首页 > 解决方案 > 在 C++ 中设置数据结构,每个类只包含一个外观

问题描述

我需要有一个集合(或任何其他数据结构),它只能包含每个类的一个实例。例如:我有一个接口 A,我有一个实现它的 A1。

我有代码:

std::set<A> myset;
A1 a1;
A1 a11;
myset.insert(a1); // should insert
myset.insert(a11);// should not insert

我希望那a11不会出现在集合中。我想用自定义比较器来做,但我不知道如何实现这个比较器。

有任何想法吗?

标签: c++data-structures

解决方案


您似乎认为std::set是一个异构容器,例如tupleor pair。但是,与大多数 C++ 标准容器一样,它是同质类型容器,因此您只能存储单一类型。

如果您要存储的所有类都派生自一个公共基础,您可能会考虑存储智能指针。例如:

struct Base { virtual ~Base() {} };
struct A1 : Base {};
struct A2 : Base {};

struct myless {
    bool operator()(const std::unique_ptr<Base>& lhs, const std::unique_ptr<Base>& rhs) const
    {
        return typeid(*lhs).before(typeid(*rhs));
    }
};

std::set<std::unique_ptr<Base>, myless> myset;
myset.emplace(new A1()); // will insert
myset.emplace(new A1()); // will not insert
myset.emplace(new A2()); // will insert
myset.emplace(new A2()); // will not insert

接下来,由于std::set根据您可以定义的比较器强制每个值是唯一的,因此您需要以比较每个实例的类型而不是值的方式定义它。就是myless这样。


推荐阅读