vector of vectors push_back

karl71 picture karl71 · Apr 5, 2013 · Viewed 88.7k times · Source

I'm designing a multilevel queue process simulator in C++ but I've got a problem when trying to implement several queues (my queues are vectors).So, "multilevel" is a 4 elements array (not vector). Inside each of those elements there is a vector (type t_PCB).

vector<vector<t_PCB>> multilevel[4];

My question is: How can i insert an element at the end of one these 4 t_PCB vectors? Thank you in advance.

I've tried the code line below but it doesn't work (error: not matching member function for call 'push_back')

multilevel[0].push_back(p); //where "p" is a t_PCB object

The line from above can not be used when talking about "multilevel" because this array only accepts arguments type: vector < t_PCB >

So, as I ask at the beginning: how can I push an object type "t_PCB" inside "multilevel"?

Answer

Andy Prowl picture Andy Prowl · Apr 5, 2013

By doing this:

vector<vector<t_PCB> > multilevel[4];

You declare an array of four zero-sized vectors, each of which can contain objects of type vector<t_PCB>. What you probably wanted to do is rather:

vector<vector<t_PCB> > multilevel(4);
//                               ^^^

This will instantiate a vector of four default-initialized objects of type vector<t_PCB>. Then, you can just do:

multilevel[size].push_back(p);

Notice, though, that vector indices (like array indices) are zero-based, so size must be less than the size of the vector.

In the above expression, the sub-expression multilevel[size] returns a reference to the size-th vector inside multilevel, and on that vector you are then invoking the member function push_back(p), which appends element p to it.