Two dimensional array question

Started by
4 comments, last by Satharis 7 years, 4 months ago

Hi Guys,

Just wondering if it is possible to somehow create and initialise a 2D array with varying sized data.

Something like this;

float item[][0] = { 1.0, 9.0, 3.5 };
float item[][1] = { 9.5, 1.2, 9.9, 7.7, 2.4, 1.8 };

And then access the data how ever I wise after that, being aware to check sizeof(item[x][y]) obviously.

Is this sort of thing possible?

Or is a std::vector better for this sort of thing?

Thanks in advance.

Advertisement

Take a step back... what are you trying to achieve?

Will the size of the individual rows change, or will it be allocated upfront? You could make it a 1d array with some clever indexing (hidden behind a class).

There are lots of ways of doing this... in terms of simplicity a vector of vectors (std::vector<std::vector<float>>) will achieve what you want with a minimum of fuss and be almost guaranteed to be leak free. But it might not be optimal for your scenario (if performance is a consideration).

if you think programming is like sex, you probably haven't done much of either.-------------- - capn_midnight

Hi there and thanks for the reply.

Each array will be static. Essentially, I want to store frame animation and each frame is a 1D array. So, I want to be able to increment or manually choose what frame I want but have it in the form of frame[n]. 'n' being the frame number.

float data_array[] = { 1.0, 9.0, 3.5,
                       9.5, 1.2, 9.9, 7.7, 2.4, 1.8 };
float *item[] = { data_array, data_array + 3 };
This will have a similar effect to what you want. You can use item[1][2] and you'll get 9.9.

Thanks Alvaro. I was driving home from work and I was thinking of a solution along very similar lines to what you have there.

I'll have a play around and see what I can come up with. :)

Personally I tend to avoid multi-dimensional arrays just because they add a lot of little things to think about like the order you're traversing them in. I mean, usually you can get the same result just by hiding the implementation behind some interface code.

But that's just me.

This topic is closed to new replies.

Advertisement