1

I'm trying to read in a directed graph adjacency list from a file. I am storing it in a map of each node to a vector of the nodes it is connected with. Below is an example line of input for the nodes connected to node 1.

1   37  79  164 155 32  87  39  113 15  18  78  175 140 200 4   160 97  191 100 91  20  69  198 196

I have the following code which compiles successfully but on running, gives a segmentation fault in the loop indicated below.

typedef map<int, vector<int> > adjList;
ifstream file;
file.open("kargerMinCut.txt", ifstream::in);
string line;
adjList al;
while(!file.eof())
{
    getline(file, line);
    stringstream buffer(line);
    int num;
    buffer >> num;
    al.insert(make_pair(num, adjList::mapped_type()));

    // the below loop causes segmentation fault
    while (!buffer.eof())
    {
        buffer >> num;
        al.end()->second.push_back(num);
    }
}

I'm new to STL so I might be missing something obvious, but please help me out.

Aakash Jain
  • 1,963
  • 17
  • 29

1 Answers1

7

For all stl containers end returns an iterator to one element after the last one. Thus you should never access this element. Your problematic line is al.end()->second.push_back(num);. You can use al->rbegin() to access the last valid element.

Ivaylo Strandjev
  • 69,226
  • 18
  • 123
  • 176