jason adams
jason adams

Reputation: 565

how to add to a map <int, list <int> >

Say I have a text file like so:

1 2
1 3
2 7
2 8 

What I would like to do is to put these in a map of linked lists. So I have initialized a map like so, map <int, list<int> > myMap;

My problem is that I do not know how to add this to the list. Normally, we can add to the map by just having myMap[someKey] = someValue; I'm having trouble adding a value to the list.

What I would like is to check whether the first int that is read is in the map, if not, create that entry, and add the second int to the list that corresponds to that key. For instance, if correctly done, line 1 should have inserted a key of 1 and a linked list with the element of 2. If the map already has that key, then the second int of that line should just be added to its linked list. For instance, line 2 should only be adding the element 3 to the 1's linked list.

What I'm hoping for is this:

key : value 
1 : 2 -> 3
2 : 7 -> 8

Here's my code:

ifstream infile;
infile.open(fname.c_str());
string line = "";
if (infile){
    while (getline(infile, line)){
       istringstream iss(line);
       int tail;
       iss >> tail;
       int edges;
       if (vertices.find(tail) == vertices.end()){
           iss >> edges;
           vertices[tail] = vertices[tail].push_back(edges);
           //I'm getting this error: no viable overloaded '='
       }
       else{
           iss >> edges;
           vertices[tail].push_back(edges);
       }
    }
}

Upvotes: 1

Views: 1784

Answers (1)

Benjamin Lindley
Benjamin Lindley

Reputation: 103761

Once you've read your two values from the file, this is all you need:

vertices[tail].push_back(edges);

This will do exactly what you are trying to do. vertices[tail] will return a reference to the list at that map location. If the list doesn't exist yet, one will be default constructed there. There is no need to check if it already existed, since operator[] will do that anyway.

Upvotes: 3

Related Questions