Getting the indexes of a 2D array #1958
-
Hi, I've made a 2D array of structs, like this:
Can you demonstrate the syntax for a print statement that will show the index for rows and columns? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
You have defined the 2d array as an array of an array so there are two indices that need to be dealt with. You could also define the 2-d array as an array of The following code is a possible implementation of the two indices approach. It has been tested on some random data and it appears to work as expected as shown in the image below. import std.array;
const u32 rows =4;
const u32 columns = 5;
struct Data {
u16 slice_header;
std::print("Row {}, Column {} : Slice header {} ",std::core::array_index(), parent.parent.sliceIndex,slice_header );
// std::print("{}", std::core::array_index() ); // <- Debug print the row, column here
};
struct Slice {
u32 sliceIndex = std::core::array_index();
std::Array<Data,rows> slice;
};
struct Frame {
std::Array<Slice, columns> slice;
};
Frame frame@0; The following is printed to the console: I kept the names as close as possible to the code you posted but Using only one index for the 2d array would not need the definition of the u32 index = std::core::array_index();
u32 row = index / columnCount;
u32 column = index % columnCount; Column major: u32 index = std::core::array_index();
u32 column= index / rowCount;
u32 row = index % rowCount; HTH. |
Beta Was this translation helpful? Give feedback.
You have defined the 2d array as an array of an array so there are two indices that need to be dealt with. You could also define the 2-d array as an array of
rows*columns
entries so I'll write the code to implement the case you posted and write all the details needed to use one index only.The following code is a possible implementation of the two indices approach. It has been tested on some random data and it appears to work as expected as shown in the image below.