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};
There's std::set
, which implements dynamic sets (dynamic means elements can be inserted or deleted). To make it work with your element
structure, you need a custom comparison function that looks only at the id
. Alternatively, you could use std::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 into std::set
or std::map
. For the difference, use std::set_difference
.
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
struct element {
int id;
float value;
element(int id_=0, float value_=0.0) : id(id_), value(value_) {}
bool& operator==(const element& e) const
{
return id==e.id && value==e.value;
}
};
element e1(1,1.0);
std::set<element> set_;
set_.insert(e1);
Checkout std algorithm for the operations you can perform.
http://www.cplusplus.com/reference/algorithm/