vendredi 1 octobre 2021

How to print graph structure (which uses vector of pointers to implement)? [duplicate]

I want to print the following graph structure. It is using vector to implement but not vector<vector>.

struct DirectedGraphNode {
  int label;
  vector<DirectedGraphNode*> neighbors;
  DirectedGraphNode(int x) : label(x) {};
};

int main() {
  DirectedGraphNode* n1 = new DirectedGraphNode(1);//create 1st node
  DirectedGraphNode* n2 = new DirectedGraphNode(2);//create 2nd node
  n1 -> neighbors = {n2};//link the 1st to 2nd
  vector<DirectedGraphNode*> graph = {n1, n2};//create graph

  /*********** start print ************/
  //print vertex node
  vector<DirectedGraphNode*>::iterator iter_pt;
  for (iter_pt=graph.begin(); iter_pt<graph.end(); iter_pt++) {
    cout << iter_pt -> label << ":";
    
    //print the neighbor nodes of each vertex
    vector<DirectedGraphNode*>::iterator iter_neighbor_pt;
    for (iter_neighbor_pt = (iter_pt -> neighbors).begin(); 
         iter_neighbor_pt < (iter_pt -> neighbors).end(); 
         iter_neighbor_pt++) {
         cout << iter_neighbor_pt -> label;
    }
    cout << "\n";
  }
}

I simplify the graph instance using only two nodes: 1 -> 2. So the expected output should be:

1: 2

2:

When I compiled using c++11, However, I got the error at those spots iter_pt -> label, iter_pt -> neighbors, and iter_neighbor_pt -> label:

error: member reference base type 'DirectedGraphNode *' is not a structure or union.

Could anyone explain why it's wrong and how to correctly print the graph structure above?

Aucun commentaire:

Enregistrer un commentaire