Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vector of vectors push_back

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"?

like image 377
karl71 Avatar asked Apr 05 '13 16:04

karl71


4 Answers

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.

like image 65
Andy Prowl Avatar answered Oct 05 '22 11:10

Andy Prowl


Declaring a two dimensional vector is similar to declaring an array. You can also use it in same way...

vector<vector<int> > vec;

for(int i = 0; i < 5; i++)
{
    vector<int> row;
    vec.push_back(row);
}

vec[0].push_back(5);
cout << vec[0][0] << endl;
like image 25
Parag Avatar answered Oct 05 '22 11:10

Parag


You are creating a array of vector<vector<t_PCB>> instead of a single object.

I think the right way to do what you want is:

vector<vector<t_PCB>> multilevel(4);
multilevel[0].push_back(p)
like image 43
Hugo Corrá Avatar answered Oct 05 '22 09:10

Hugo Corrá


You can create a vector instead of array:

std::vector< std::vector<t_PCB>> multilevel(4); // 2 dim array, 1st dim is 4

and then you can push_back at the end of the vector indexed with WHICH this way:

multilevel[WHICH].push_back(p)
like image 39
4pie0 Avatar answered Oct 05 '22 09:10

4pie0