Search code examples
c++vectormultidimensional-arraypush-back

handling a 2 dimensional vector c++


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.


Solution

  • 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:

    for(int i=1;i<112;i++){
        n_2.push_back(vector<struct nodo>(112-i));       
        for(int j=1;j<112-i;j++){
          n_2[i][j].last_prod=j;
        }
    }
    

    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:

    #include <array>
    using namespace std;
    
    // allocate an array of 112 <struct nodo> arrays, each of size 112
    array<array<struct nodo, 112>, 112> n_2;
    for (int i = 0; i < 112; i++)
    {
        for (int j = 0; j < 112; j++)
        {
            n_2[i][j].last_prod = j;
        }
    }
    

    Or alternatively, if I don't have a compiler that supports C++11:

    #include <vector>
    using namespace std;
    
    // allocate a vector of size 112 of <struct nodo> vectors, each of size 112
    vector<vector<struct nodo> > n_2(112, vector<struct nodo>(112));
    for (int i = 0; i < 112; i++)
    {
        for (int j = 0; j < 112; j++)
        {
            n_2[i][j].last_prod = j;
        }
    }
    

    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.