I’m making a C++ Maze program using disjoint sets and the Union/Find operations.
I have a MakeSet(int x) function which creates a new Node for every integer element x in the maze. (i.e 1 to 16 for a 4×4 maze). Thus initially every element is in its own set.
My MakeSet looks like this
void Maze::MakeSet(int x)
{
Node *root = new Node;
root->label = x;
root->parent = NULL;
}
But in the CreateMaze() function I have to call MakeSet many times to get all the elements into their own set initially. Thus, the root will keep being overwritten. How do I dynamically allocate many different nodes? Should I keep them separated in an array?
You already allocate a new
Node, you are just not keeping it. You need to change the function to returnNode*, and store the results in an array or a vector.An even better approach would be to do
Nodeinitialization in a constructor:You can now create all sets in a loop, and store pointers to them in an array: