mary
mary

Reputation: 25

fast creating a graph from a text file in c++

I want to make a graph from a text file containing 36692 nodes and each line of the text contains the source and the target node of an edge of the graph. I used the igraph library to create the graph. I wrote the following code but it is too slow. how can I improve it?

  igraph_empty(&graph, 36692, 0);
  ifstream inputFile("Email-Enron.txt");
  string line;

  while (getline(inputFile, line))
  {
        istringstream ss(line);       
        int v1, v2;
        ss >>  v1 >> v2 ;
        igraph_add_edge(&graph, v1, v2);
   }

Upvotes: 2

Views: 869

Answers (1)

Stephan Lechner
Stephan Lechner

Reputation: 35154

If the file read is the bottleneck (which you actually should profile), I'd suggest to get rid of the superfluous stringstream variable.

If each line contains exactly two numbers and nothing else, then reading in the numbers pairwise directly from the stream works as well, because operator >> treats a new line as a white space and ignores it the same way as it ignores blanks:

  igraph_empty(&graph, 36692, 0);
  ifstream inputFile("Email-Enron.txt");

  int v1, v2;
  while ( (inputFile >>  v1 >> v2) ) {
        igraph_add_edge(&graph, v1, v2);
  }

Upvotes: 3

Related Questions