zaratushtra
zaratushtra

Reputation: 53

a digraph representation by structs

I would like to create a digraph. Each Edge has information about destination Node and origin Node . In addition, each Node has information about list of incomingEdges and outgoingEdges .

I have an adjacencyMatrix [][] of graph and I want to read the matrix and and create a new graph.

here is code;

  struct Node
    {
       vector<Edge *> incomingEdges;
       vector<Edge *> outgoingEdges;
    };

    struct Edge
    {

       struct Node destination;
       struct Node origin;

    };

. . . .

for(int i=0; i<totalNodes; i++)
{
    struct Node nodei;
}

. . . . .

for(int i=0; i<totalNodes; i++)
{
    for (int j=0; j<totalNodes; j++)
    {
        if ( adjacencyMatrix[i][j] == 1)
        {
            struct Edge edgeij;
            edgeij.destination=nodej;
            edgeij.origin =nodei;
            nodei->outgoing.push_back(edgeij); // ???
            nodej->incoming.push_back(edgeij); // ???

        }
    }
}

I m not familiar to C/C++. obviously I need some help to improve it. How can I push_back to a vector of pointer declared in a struct ?

Upvotes: 0

Views: 143

Answers (1)

quantdev
quantdev

Reputation: 23793

When you do :

    if ( adjacencyMatrix[i][j] == 1)
    {
        struct Edge edgeij;
        edgeij.destination=nodej;
        edgeij.origin =nodei;
        nodei->outgoing.push_back(edgeij); // ???
        nodej->incoming.push_back(edgeij); // ???
    }

The edgeij object is destroyed at the end of the block, making it pretty useless (and the code does not compile anyway, since you try to push an object where a pointer is expected)

Since your vector is expecting a pointer, you should use a dynamically allocated Edge :

    Edge* edgeij = new Edge;
    edgeij.destination=nodej;
    edgeij.origin =nodei;
    nodei->outgoing.push_back(edgeij);
    nodej->incoming.push_back(edgeij);
    // now, do not forget to properly delete resources allocated with new

A better design solution would be to avoid raw pointer altogether, and prefer smart pointers, e.g. std::vector<std::unique_ptr<Node>>.

Upvotes: 1

Related Questions