Problems accessing data in a vector of lists

I'm having trouble accessing data in one of my data structures. I have a vector of strings and a vector of lists of strings.

1
2
3
4
5
6
7
8
9
10
11
class graph
   {
   private:
      vector<string> IDs;
      vector< list<string> > Prereq;
      
   public:
      graph();       //Constructor
      ~graph();      //Destructor
      void load();   //Loads courses and prereqs
   };


1
2
3
4
5
if(!exist)  //If course doesn't exist, add course to list and place prereq in proper place
   {
   IDs.push_back(course);
   Prereq[IDs.size() - 1].push_back(prerequisite);
   }


I get a segmentation fault on the line
Prereq[IDs.size() - 1].push_back(prerequisite);
As far as i can tell it should access the list at that location and push 'prerequisite' onto it.

What am I missing?
Does that element exist in Prereq?

You are using the size of the other vector to index Prereq.

You're accessing the index value of the last value in IDs in Prereq. For the last value of Prereq use Prereq.size().
Yes it does exist. Notice that a string was pushed into IDs right before that line so the lowest number possible that could result from "IDs.size() - 1" is 0 which is still valid. I did a cout of the size of IDs and it shows '1' and then once it gets to that line it crashes.

The two are designed to run in parallel. The vector holds a class number and the second vector holds a list of prerequisites to that class. The class number in vector 1 and the prerequisites in vector 2 will both be under the same subscript of their corresponding vectors...make sense?

if a class CSCI 340 has prerequisites CSCI 240 and CSCI 241 the vectors will look like this:

Vector 1:
[0] - CSCI 340

Vector 2:
[0] - CSCI 240, CSCI 241

I tried using Prereq.size()...it still crashes
I even tried putting just Prereq[0].push_back(prerequisite); and even that didn't work.
Last edited on
Can you print out the size of Prereq before you call push_back?

I don't see where you call push_back onto Prereq, which means that Prereq[ 0 ] is not valid.
(operator[] on vectors assumes the element exists; it does not create it first).
Hmm...yeah i see what you mean. I'm trying to push onto the list that should be contained in Prereq[0] but it may not exist. I guess my question then is what do i do?

I need to push a string onto a list contained in the slot of a vector. Do i need to first create a list, push the string onto it and then push the list into the vector? I'm really not sure how to do that. Any suggestions?
Yes, that's what you need to do.

One way is:

1
2
3
list<string> l;
l.push_back( "foo" );
Prereq.push_back( l );


or, you can do it in 1 line of code

 
Prereq.push_back( list<string>( 1, "foo" ) );


as in this case, list has a constructor that takes a count and an element, and initializes the list with count copies of the element.
Thanks! that took care of it
Topic archived. No new replies allowed.