That code looks like plain C rather than C++.
Step 1 is to understand why the algorithm uses
dynamic memory allocation. What does the algorithm(s) do?
Step 2 is to know what options does the C++ have for such tasks.
1 2
|
int V = 3, E = 3;
struct Graph* graph = createGraph(V, E);
|
That is C. A function creates an object.
C++ structs do have constructors to create the object:
1 2
|
int V = 3, E = 3;
Graph graph( V, E );
|
That, however, is suspicious. I can claim that the graph has 1 vertex and 7 edges, and when I fill data for those edges, enter 13 unique edges. 1 != 13. My lies won't be caught soon enough.
But I digress. Lets make believe. Convert the createGraph() into constructor:
1 2 3 4 5 6 7 8 9 10
|
struct Graph
{
Graph(int V, int E)
: V(V), edge(E) // member initializer list syntax
{
}
int V;
std::vector<Edge> edge;
};
|
Can it be that short?
The
struct Graph* graph = (struct Graph*) malloc( sizeof(struct Graph) );
is unnecessary, because the main can have Graph variable with automatic storage duration.
The
graph->edge = (struct Edge*) malloc( graph->E * sizeof( struct Edge ) );
reveals that Graph.edge is practically a dynamic array with E elements.
Constructor of std::vector does that.
Vectors edge.size() gives us the E, if we need it; no need for redundant member.
Likewise, the
1 2
|
struct subset *subsets =
(struct subset*) malloc( V * sizeof(struct subset) );
|
is clearly an array of V elements. std::vector is fine for that too.