I need to set up and access a two dimensional vector of structure in C++.
My structure is defined as:
struct nodo{
int last_prod;
int last_slot;
float Z_L;
float Z_U;
float g;
bool fathomed;
};
I defined the vector as:
vector<vector<struct nodo> > n_2;
Now,I need to create several elements of n_2, which will then be vectors again, and then access the single members of them.
How can I achieve that? that is the piece of code I have so far:
for(int i=1;i<112;i++){
n_2.push_back(vector<struct nodo>(111-i));
for(int j=1;j<112-i;j++){
n_2[i][j].last_prod=j;
}
}
which doesn’t work.
A vector is size 0 until you tell it to resize, or unless you initialize it with a specific size. Pass the size of your vector in when you create it:
Also, it looks like you are skipping over the 0th index, which means your first value in your array will be skipped. That is probably undesired.
Finally, if your array is a constant size, consider using std::array rather than std::vector. Note that std::array is a C++11 feature and may not be available depending on your compiler.
If I were writing this code, I’d probably write it like this:
Or alternatively, if I don’t have a compiler that supports C++11:
Even more ideally, you should use a 1 dimensional vector, and simply treat it as a 2 dimensional vector. This way, you can do a single allocation of memory all at once rather than 112 smaller allocations. This is getting pretty nitpicky but obviously a O(1) solution is better than an O(n) solution which is better than a O(n^2) solution in terms of allocations since allocations are slow.