Accessing List inside Vector

This code compiles but I wanna make sure the list is stored in the vector. How would I be able to print out the list from the vector?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
  int main()
{
   list< pair<int, float> > lister;
   vector< list < pair <int , float> > > adjlist;
   int values, vertex_, n;
   float weight_;
   ifstream infile;
   infile.open("Graph1.txt");
   if(!infile)
   { cout<<"Error opening File"<<endl;
     return 0;
   }
  infile>>values;
  cout<<"There are "<<values<<" nodes in this graph"<<endl;
  string line;
  while(getline(infile, line))
 {
    istringstream iss(line);
    iss>>n;
    while(iss>>vertex_>>weight_)
    {
      
      cout<<n<<" -> "<<vertex_<<" with weight "<<weight_<<endl;
      lister.push_back(make_pair(vertex_, weight_));
    }
   
    adjlist.push_back(lister);//inserts list into vector 
    lister.clear();// clears list for next vertex
    
 }
return 0;
Which list? That vector may contain any number of lists. If you know how to iterate a vector, then there is nothing new for you here. Each element of the vector will be a list that you can operate on as you like.
The list from the 2nd while loop. The vector contains 5 lists one for each vertex for the graph. I can iterate the vector but every time I try to access the pairs in the list I get a segmentation core dump error. I guess my question more specifically would be how to access the pairs in the list from the vector?
This is what I had :
1
2
3
4
5
6
7
8
9
for (int i = 0; i < adjlist.size(); i++) {
       
         
        list< pair<int, float> >::iterator itr = adjlist[i].begin();
         
        while (itr != adjlist[i].end()) {
            cout<<(*itr).first<<" "<< (*itr).second<<endl;
            itr++;
        }
Last edited on
Perhaps writing it more simply could help make the error more visible. Try:
1
2
3
4
5
for(auto some_list : adjlist) {
    for(auto some_pair : some_list) {
        std::cout<<some_pair.first<<" "<<some_pair.second<<std::endl;
    }
}

Does this work?
No, it did not work.
Did you get any compilation errors? Runtime errors?
Topic archived. No new replies allowed.