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;} }; 
5
  • 2
    Are a and b going to be know at compile time or run time? If run time I suggest you use a std::vector. Commented Jul 15, 2016 at 18:38
  • Hello @NathanOliver, and be will be known at run time. Commented Jul 15, 2016 at 18:39
  • @johnwoe Please post tt. It may be able to be used in vector, but has to have proper copy semantics first. Commented Jul 15, 2016 at 18:44
  • @PaulMcKenzie check edit Commented Jul 16, 2016 at 2:35
  • If the 2d array is statically sized, you should consider looking into std::array over std::vector if efficiency is a concern. stackoverflow.com/questions/4424579/… Commented Jul 16, 2016 at 4:25

2 Answers 2

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; }; 
Sign up to request clarification or add additional context in comments.

2 Comments

for loops are allowed in inline functions within class definitions?
Yes. The function may/will not be inlined but they are certainly allowed.
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.