c++ - 在 C++ 中设置数据结构,每个类只包含一个外观
问题描述
我需要有一个集合(或任何其他数据结构),它只能包含每个类的一个实例。例如:我有一个接口 A,我有一个实现它的 A1。
我有代码:
std::set<A> myset;
A1 a1;
A1 a11;
myset.insert(a1); // should insert
myset.insert(a11);// should not insert
我希望那a11
不会出现在集合中。我想用自定义比较器来做,但我不知道如何实现这个比较器。
有任何想法吗?
解决方案
您似乎认为std::set
是一个异构容器,例如tuple
or 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
这样。
推荐阅读
- python - scikit-learn - TypeError:fit()缺少1个必需的位置参数:'y'
- php - 根据第二列从一列中选择数据
- flutter - Flutter - 使用 .popUntil 传回数据
- python - 如何在包含标签中缓存模板
- node.js - Node.js 10 HTTPS 服务器拒绝连接
- python - 告诉geojson将数据保存为UTF8?
- javascript - 在 Firebase 中更新密码(Angular 5)
- c# - SQL Azure 每 10 秒延迟一次响应
- json - Terraform - 数据依赖于数据
- ios - iOS中的背景图像/视频上传