集合论数据结构
我有相当函数式编程的背景,但我不习惯(高效的)C++ 数据结构。我需要一个保留多个元素的数据结构,如struct element
中所示。在集合中,字段id应该是唯一的。
我想像集合论中一样执行非常快速的集合比较,例如在比较集合 {x1,x2,x3}
和 {x4,x5}
我想要确定交集 {x5}
(或 {x2}
在本例中相等)并从其他集合中减去集合,例如 {x1,x2,x3 } \ {x5} = {x1,x3}
。
C++ 宇宙中是否存在……“集合论”数据结构?
struct element {
int id;
float value;
};
struct element x1 = {1, 1.0};
struct element x2 = {2, 2.0};
struct element x3 = {3, 3.0};
struct element x4 = {3, 3.1};
struct element x5 = {2, 2.0};
I come from a rather functional programming background and I'm not used to (efficient) C++ data structures. I need a data structure that keeps multiple elements like depicted in struct element
. In the collection, the field id shall be unique.
I want to perform a very fast set comparison like in set theory i.e. for example when comparing the sets {x1,x2,x3}
and {x4,x5}
I want to determine the intersection set {x5}
(or {x2}
which are equal in this case) and substract sets from other sets like e.g. {x1,x2,x3} \ {x5} = {x1,x3}
.
Is there a ... "set theoretic" datastructure out there in the C++ universe?
struct element {
int id;
float value;
};
struct element x1 = {1, 1.0};
struct element x2 = {2, 2.0};
struct element x3 = {3, 3.0};
struct element x4 = {3, 3.1};
struct element x5 = {2, 2.0};
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
std::set
实现了动态集(动态意味着可以插入或删除元素)。为了使其适用于您的element
结构,您需要一个仅查看id
的自定义比较函数。或者,您可以使用std::map
,这可能更适合您的问题。要查找两个集合的交集,请使用
std::set_intersection
算法。这需要排序范围,其中包括 std::set 或 std::map 中的迭代器范围。对于差异,请使用std::set_difference
。There's
std::set
, which implements dynamic sets (dynamic means elements can be inserted or deleted). To make it work with yourelement
structure, you need a custom comparison function that looks only at theid
. Alternatively, you could usestd::map<int, float>
, which might be a better fit to your problem.To find the intersection of two sets, use the
std::set_intersection
algorithm. That requires sorted ranges, which includes ranges of iterators intostd::set
orstd::map
. For the difference, usestd::set_difference
.只是想提一下,因为在处理集合时有一个非常好的数据结构,但它不能满足您的所有需求,
但是如果您有以下要求,您仍然可以记住它:
1)查询元素属于哪个集合
2)不同集合的
并集都在亚对数时间内,即几乎恒定。它称为不相交集数据结构
http://en.wikipedia.org/wiki/Disjoint-set_data_struct
Just want to mention this as there is a really great data structure when dealing with sets but it doesnt suites all your needs,
But still you can keep it in mind if you have requirements like,
1) Querying to which set an element belongs
2) Union of different sets
Both in sub-logarithmic time i.e. Almost constant. Its called Disjoint set Data structure
http://en.wikipedia.org/wiki/Disjoint-set_data_structure
检查标准算法以了解您可以执行的操作。
http://www.cplusplus.com/reference/algorithm/
Checkout std algorithm for the operations you can perform.
http://www.cplusplus.com/reference/algorithm/