Search code examples
c++formatistream

How to make formatted file read for Adjacency list?


I have adjacency list for graph typedef map<int, vector<int> > AdjacencyList;

Now I want to fill it from file which looks like this:

1 234 432 654 876 ...
2 32 521 323 122  ...
3 654 4 75 652    ...
....

So the first element in a row is vertex and the rest elements are adjacent vertices. How do I read it?


Solution

  • Use getline() to read each line into a string, and then construct istringstream from the string and read numbers from there. Something like this, but with better error checking.

    std::ifstream file;
    // open file etc.
    std::string line;
    
    AdjacencyList al;
    while (!file.eof())
    {
        getline(file, line);
    
        std::istringstream buffer(line);
        int num;
        buffer >> num;
        auto it = al.insert(std::make_pair(num, AdjacencyList::mapped_type()).first;
        while (!buffer.eof())
        {
            buffer >> num;
            it->push_back(num);
        }
    }