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};
Checkout std algorithm for the operations you can perform. http://www.cplusplus.com/reference/algorithm/
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
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
.