Coming from a C background, I'm trying to teach myself C++. I have been trying to implement the UnionFind data structure. I have a class as follows :-
class UnionFind
{
private:
int count;
UnionFind* parent;
int val;
public:
UnionFind(int _val) : count(1), parent(this), val(_val) {
printf("UnionFind(): parent=%p this=%p\n", parent, this);
}
~UnionFind() {
printf("~UnionFind()\n");
}
int getcount()
{
if (parent == this)
return count;
return Find()->count;
}
int getval() { return val; }
void setparent(UnionFind* _parent) { parent = _parent; }
void setcount(int _count) { count = _count; }
// Does a union of 2 sets
void Union(UnionFind* u)
{
printf("Union(%d: this=%p, %d: u=%p)\n", val, this, u->getval(), u);
UnionFind* this_parent = Find();
UnionFind* u_parent = u->Find();
printf("this_parent=%p u_parent=%p\n", this_parent, u_parent);
if (this_parent == u_parent)
return;
if (this_parent->getcount() > u_parent->getcount()) {
this_parent->setcount(this_parent->getcount() + u_parent->getcount());
u_parent->setparent(this_parent);
} else {
u_parent->setcount(this_parent->getcount() + u_parent->getcount());
this_parent->setparent(u_parent);
}
}
// Returns the parent
UnionFind* Find()
{
//printf("%d: Find(%p) = ", val, this);
UnionFind* temp = parent;
while (temp != temp->parent)
temp = temp->parent;
//printf("%p\n", temp);
return temp;
}
};
Later on I try to populate a vector with some instances of UnionFind
as follows :-
vector<UnionFind> vecs;
for (int i = 0; i < N; i++)
vecs.push_back(UnionFind(i));
Running this code shows that the UnionFind objects all have the same address. I suspected(and confirmed) that this is because the destructor of UnionFind is being called in each iteration of the loop.
My question is :-
- I realise that I could create a vector of pointers to UnionFind objects as
vector<UnionFind*>
to solve this problem, but is that really the way to go? I read that unlike in C, it might be possible to solve a lot of problems in C++ without resorting to new/malloc or delete/free. What is the C++ way to solve this problem?
[EDIT]
Typo corrected.
[EDIT 2]
I'm trying to implement a disjoint-set/union-find data structure. "parent" will point to itself initially, but as unions occur parent might point to a different object.
[EDIT 3]
Added in full code.