2D lattice, quick question

Hello,

I have to work with a 2D lattice.
I have been storing it as a 1D array.

Would storing it as a 2D array improve the program in terms of speed and readability?

Thanks,

Best,
Clodi
in terms of speed
No.
readability
Maybe. Not if you bother to make adequate access functions for your 1D array and/or wrap it in class.

I would say that its best to model your data structure to suit the real world entity that you're modelling, i.e. a chess board, would require a 2d matrix.
OK

so.. still..

class Lattice
{
int array[ 100 ];
};


worse off than

class Lattice
{
int array[ 10 ][ 10 ];
};


yes, it is wrapped in a class but was wondering if 2D stuff was actually stored in 1D arrays in the industry for speed or something but apparently not..

Thanks!

Whether you declare you array as 1d, 2d, or nd, the array itself is stored in contiguous memory so technically its a 1d array. If you declare a 2d array you can still access it using a pointer to its index in memory as if it's a 1d array.
I would say that its best to model your data structure to suit the real world entity that you're modelling, i.e. a chess board, would require a 2d matrix.
http://www.cplusplus.com/forum/articles/17108/
View and model does not have to be the same. Usual approach for chess board is to just have a list of pieces

View and model does not have to be the same. Usual approach for chess board is to just have a list of pieces


I was merely expressing my opinion, you do not necessarily have to agree.
OK let me call the fight off.
Thanks for the info though. All of you.

I think that a 2D array makes more sense than a 1D one to describe something that is 2D in nature. Stack-wise / performance-wise and everything else-wise there is NO difference so it's just up to the programmer.

Basically the ONLY difference is that if you declare it as 2D for a 2D-type object, you avoid having to do the index to coordinates and coordinates to index yourself.
On the other end, if you declare a 2D array for a 1D-type object things are gonna get crazy crazy crazy.

Thanks
Stack-wise / performance-wise and everything else-wise there is NO difference so it's just up to the programmer.
Yes, for static arrays. If you are going to use dynamic memory allocation, avoid 2D arrays.

you avoid having to do the index to coordinates and coordinates to index yourself.
If you have to use dynamic 2D arrays, consider making class with access function, so you coud do something like:
1
2
Array2D arr(8, 6); //8x6 2D array
arr(3, 1) = 10; //Loke arr[3][1] = 10 for usual arrays 
Topic archived. No new replies allowed.