-1

So basically I have a file that his lines compose a graph, in which the 1st line is the number of vertices and arcs and the rest is the connections. The problem is that in my graph printing function for some reason it doesn't print anything.

Program:

#include <iostream>
#include <vector>
#include <cstdlib>
#include <cstring>
#include <cstdio>
using namespace std;


void AlgInit(char str[],vector<vector<int>> graph)
{
    int m,n,tokens;
    FILE* entry;
    entry = fopen(str,"r");
    
    tokens = fscanf(entrada,"%d %d",&n,&m);
    
    graph = vector<vector<int>>(n,vector<int>());
    for(int i=0; i<n;i++)
    {
      int u,v;
      fscanf(entry,"%d %d",&u,&v);
      graph[u-1].push_back(v-1);
    }
    fclose(entrada);
}

void printGraph(vector<vector<int>> g)
{
  for(int i=0;i<g.size();i++)
  {
    for(int j=0;j<g[i].size();j++)
    {
      printf("%d %d",i+1,g[i][j]+1);
    }  
  }
}

int main(int argc,char** argv)
{
  vector<vector<int>> graph1;
  AlgInit(argv[1],graph1);
  printf("%s\n",argv[1]);
  printGraph(graph1);
  exit(0);
}
Damian
  • 78
  • 3
Martim Correia
  • 483
  • 5
  • 16
  • Could please provide the first ~5 lines of an example file that you want to read? – Nano Byte Mar 30 '21 at 16:37
  • You are passing the graph as a _call-by-value_ which makes it work on a local, detached copy. If you want to pass the graph as a modifiable object, you would need to do it by `void AlgInit(const char str[],vector> &graph)` which is _call-by-referrence_. – Nano Byte Mar 30 '21 at 16:40
  • Handy reading: [What's the difference between passing by reference vs. passing by value?](https://stackoverflow.com/questions/373419) – user4581301 Mar 30 '21 at 16:43

1 Answers1

1

The Problem here is the signature of your function declaration, which calls the graph by-value and not by-referrence. The latter one is needed to get a modifiable version of the object and not just a local copy.

Since your version did a call-by-value, the graph object (initialized as empty vector) is not modified by the AlgInit, and thus the print method has nothing to do.

The function should thus look like this, whith the & making the difference here

void AlgInit(char str[],vector<vector<int>> &graph)

As suggested in the comment, some further reading: What's the difference between passing by reference vs. passing by value?

Nano Byte
  • 106
  • 3