user1313867
user1313867

Reputation: 31

reading&maintaining graph in C++

I have a text file from where I would read an undirected graph. The format is as follows:

1 2 3
2 1
3 1

Where every first element in the row corresponds to a vertice, and the rest is basically the adjacency list for the vertice.

So my two questions are:

Thanks in advance for the help.

Upvotes: 1

Views: 1395

Answers (1)

Guy Sirton
Guy Sirton

Reputation: 8401

I would store graphs as either a adjacency list or a matrix, in C++ here is one way of coding this. Depending on performance/storage requirements you may need to tweak this.

vector< list<int> > graph;

or you could use an adjaceny matrix.

vector< vector<bool> > graph;

As for reading your file format, I would use getline() to read the file line by line and then parse each line for the integer values (perhaps with istringstream), something like this perhaps:

ifstream f;

vector< list<int> > graph;

f.open(fileName);
while(!f.eof() && !f.fail())
{
    char line[1024]; // Reserve enough space for longest line
    f.getline(line, 1024);

    istringstream iss(line, istringstream::in);

    int vertex;
    iss >> vertex;
    if(!f.fail())
    {
        if(vertex > graph.size()) // Max number of vertex is unknown
        {
            graph.resize(vertex); 
        }
        vertex--; // From your 1-base to zero-based
        list<int>& vertex_list = graph[vertex];
        do
        {
            int to_vertex;
            iss >> to_vertex;
            if(!iss.fail())
            {
               vertex_list.push_back(to_vertex - 1);
            }
        } while(!iss.eof() && !iss.fail());
    }
}

Upvotes: 2

Related Questions