简体   繁体   中英

Array of array of structs

Is it possible to declare an array consisting of other arrays (with variable sizes) consisting of structs in C++? It would be really nice if there was an easy and efficient way (using for) to iteration over all structs inside an element of the array.

The struct is defined like this:

struct Number
{
  int x;
  int y;
};

For example, the data is something like:

{
    { {0,0}, {0,1} },
    { {0,0}, {0,1}, {1,0}, {0,0} },
    { {0,0}, },
    { {0,0}, {4,0} }
}

I would like to use this for a self made clock consisting of an Arduino Uno, an Ethernet shield, an RTC and a LED array. The solution shouldn't use more memory than needed. That's why I don't use a two dimensional array.

You can use Standard C++ For Arduino . It implements a std::vector

With that, you can use a vector of vectors

struct Number
{
  int x;
  int y;
};

using MultiNum = std::vector<std::vector<Number>>;

However, it is of a worthy note that, Arduino's memory is really small, and you should really have upper bounds to your memory usage. A vector of a vector without smartly using reserve may waste some memory...

Another option is:

Number x[][4] =
    {
    { {0,0}, {0,1} },
    { {0,0}, {0,1}, {1,0}, {0,0} },
    { {0,0}, },
    { {0,0}, {4,0} }
    };

Of cause, that dictates the fixed memory consumed at compile time. (A 4x4 Matrix of Number ).

Yes, Number* var[]; or Number** var; . Case closed :)

EDIT: oh, you swapped to C++... Than save yourself a headache and use the std::vector. Well... you can make your own Vector even in C, but no templates.

如果您关心的是内存,您可以随时声明Number **var并在需要时手动分配和重新分配空间。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM