在C++中设置数据结构,其中只包含每个类的一个外观

Raz*_*hen 0 c++ data-structures

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

我有代码:

std::set<A> myset;
A1 a1;
A1 a11;
myset.insert(a1); // should insert
myset.insert(a11);// should not insert
Run Code Online (Sandbox Code Playgroud)

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

有任何想法吗?

Joh*_*nck 6

你似乎认为std::set是一个异类容器喜欢tuplepair.但是,与大多数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
Run Code Online (Sandbox Code Playgroud)

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