user2149890
user2149890

Reputation: 9

Vector of lists

So I am trying to write a function that takes two arguments, list<item> myList, and int num_items and creates a vector of new lists. Each item has data member ID, which is the index in the vector of which list the item should be added to. The ID of any item is guaranteed to be no greater than (num_items - 1). Here is my code:

vector<list<item>> createVector(list<item> myList, int num_items) {
   vector<list<item>> myVector;
   myVector.reserve(num_items);

   for(item& i : myList)
      myVector[i.ID].push_back(i);

   return myVector;
}

This is causing a segmentation fault whenever I try to call push_back() to add an item to a list in the vector. I know how to implement the function using pointers, however the type returned by the function must be an actual vector of lists not pointers to them, so I can't use dynamic memory allocation. Any help would be greatly appreciated. Thanks.

Upvotes: 0

Views: 818

Answers (2)

Remy Lebeau
Remy Lebeau

Reputation: 598448

reserve() merely allocates a block of memory. It does not create the list objects that you are calling push_back() on. You need to use resize() instead of reserve() to create them:

myVector.resize(num_items);

Or better, pass the count to the constructor directly instead:

vector<list<item>> myVector(num_items);

Upvotes: 3

Mike Seymour
Mike Seymour

Reputation: 254771

reserve only reserves space for that many vector elements; it doesn't create any elements, so you can't access them. You want to use resize (or just pass the size as a constructor argument), to populate the vector with valid, empty lists.

Upvotes: 0

Related Questions