0

I have the following arrangement. I cannot change any of the vectors to array or anything else due to other constraints.

struct shelf {
  std::vector<int> books;
}
std::vector<shelf> all_shelves;

all_shelves.reserve(sizeof(shelf)*10);

I reserve the memory for shelves in the last line.

Now how do I reserve the memory that does has the effect like this ?

all_shelves[4].books_per_shelf.reserve(6*sizeof(books)); 

Currently, I am forced to do this:

struct shelf dummy_shelf;
dummy_shelf.books = 6;
all_shelves.push_back(dummy_shelf);

Can't I access the memory I had reserved earlier ?

I'm aware of the size and capacity implementation under the hood in <vector>. Is there any method that allows me access nth element without pushing back explicitly ?

  • `reserve` and `resize` take a number of items, not a size in bytes. And seems like you're looking for `resize` rather than `reserve`. – Mat Jun 03 '20 at 19:40
  • `vector::reserve` only reserves memory for contained objects, it does not create them. At the same time `vector` only allows accessing objects that were already created. So there is nothing for you to access just after `reserve`. – user7860670 Jun 03 '20 at 19:41
  • @user7860670 thank you for the clarification! I learnt it the harder way, (some segfaults) –  Jun 03 '20 at 19:44
  • @Mat thank you for correcting me there! could you please add an example of resize, modified for my use ? https://stackoverflow.com/questions/42249303/how-can-i-push-back-data-in-a-2d-vector-of-type-int#comment101535824_42249538 this comment confuses me more. –  Jun 03 '20 at 19:44

0 Answers0