0

I want to define a 2D array of structures in a class in C++, how should I do it, here is an example approach for a struct tt

class swtlvn{
private:
int a,b;
tt yum[a][b];
};

Can this be done in some way? This AoS will be used by all the member functions of the class/ultimatey defined object so it cant be defined inside a member function. Having it defined externally is going to be a hassle so no can do.

EDIT:

struct tt{
int a,b,c;
tt(){}
tt(int aa,int bb,int cc){a = aa; b = bb; c = cc;}
};
johnwoe
  • 1
  • 1

2 Answers2

1

Without knowing more, I would say you should use something similar to:

 class Foo {
 public:
    Foo(int _a, int _b) : a(_a), b(_b) {
        yum.resize(a);
        for (size_t i = 0; i < a; i++) {
           yum[i].resize(b);
        }
    }
 typedef std::vector<std::vector<tt> > TtVector2D;
 TtVector2D yum;
 };
Phil
  • 5,822
  • 2
  • 31
  • 60
1

Can this be done in some way

If tt has proper copy semantics, then one solution is to use std::vector<std::vector<tt>>:

#include <vector>
struct tt
{
    int a,b,c;
    tt(int aa=0, int bb=0, int cc=0) : a(aa), b(bb), c(cc) {}
};    

class swtlvn
{
   private:
     int a,b;
     std::vector<std::vector<tt>> yum;

   public:
     swtlvn(int a_, int b_) : a(a_), b(b_), 
                               yum(a_, std::vector<tt>(b_)) {}
};

int main()
{ swtlvn f(10, 20); } // for example

Also, once you have a std::vector, I don't recommend using extraneous member variables such as a and b to denote the size. A vector knows its own size by utilizing the std::vector::size() member function.

PaulMcKenzie
  • 34,698
  • 4
  • 24
  • 45