OK, I know that in C++ a - let's say 2-dimensional - array can be initialized this way :
int theArray[5][3] = {
{1,2,3},
{4,5,6},
{7,8,9},
{10,11,12},
{13,14,15}
};
Now, what if I want to use pre-existing arrays as theArray
's elements?
E.g.
// A, B, C, D,... have already been declared as :
// `const U64 A[] = { 1,2,3,4 };` etc...
const U64 multiDimArray[12][64] = {
A, B, C, D, E, F,
G, H, I, J, K, L
};
This one, throws an error though :
cannot initialize an array element of type 'const U64'
(aka 'const unsigned long long') with an lvalue of type 'const U64 [64]'
I see the point, but hopefully you can see mine.
Is there a workaround so that I can easily achieve the same thing? (Any suggestion - perhaps something using Boost? - is welcome)
Initialize Array of Arrays To initialize an array of arrays, you can use new keyword with the size specified for the number of arrays inside the outer array. int[][] numbers = new int[3][]; specifies that numbers is an array of arrays that store integers.
In the square brackets, we have to specify the length of our array. In option(b), (c) and (d) square brackets are mission.So they are an incorrect way of initializing the array. Square brackets must be used to initialize an array as in option(a).
If the array is not initialized at the time of declaration or any time after that then it will contain some random values in each memory position.
An array doesn't check boundaries: In C language, we cannot check, if the values entered in an array are exceeding the size of that array or not. Data that is entered with the subscript, exceeds the array size and will be placed outside the array. Generally, on the top of the data or the program itself.
If you use C++11, the initializer list for an array
is flexible:
std::array< array<U64, 64>, 12> multiDimArray = {
A, B, C, D, E, F,
G, H, I, J, K, L
};
will work fine, assuming A..L
are std::array<64, U64>
.
The array does have no overhead to the c-style array. Click here for official reference.
"The size and efficiency of array for some number of elements is equivalent to size and efficiency of the corresponding C-style array T[N]." (From the reference)
I said "flexible", since you can use a mixed initializer-list like this:
std::array<int, 3> first_row = {1,2,3};
std::array<array<int, 3>, 2> a={
first_row,
{2, 2, 2}
};
You can use this as a fixed-size array, with the same operations:
a[1][2]=2; a[0][1]=1; a[0][2]=3;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With