Say I have struct S:
struct S {
const int i;
const bool b;
}
And I want to create an (non-const) array of this struct like so:
std::array<S, 16> arr;
for(int i = 0; i<arr.size(); i++)
arr[i] = { i, i%2==0 };
Then the compiler will complain that I didn't initialize the a const variable when I initialized the array.
I tried doing it with a vector as an intermediary. But int the function I'm writing I have to pass the original array in another struct, and return that other struct.
struct OtherStruct {
const std::array<S,16> sArray;
};
OtherStruct f() {
std::vector<S> vec(16);
for(int i = 0; i<16; i++)
vec.push_back({ i, i%2==0 });
return { vec.data() };
}
But that didn't work either. I hoped that passing the pointer to the vector data would be cast into a C-style array, from which an std::array could be made. What is the cleanest way to fix this?
I'm working with C++11.
Note that this example is a gross simplification. The line arr[i] = { i, i%2==0 };
would be replaced by a function that parses incoming network data. The actual array is way bigger and the struct is also more complicated. None of the data that will populate the struct will be known at compile time, only the layout.
createAlternatingOnesZeros()`.– Marek R Nov 02 '22 at 09:23, which I'm not able to instantiate. And a braced initializer list is also not possible because the size of the array is 800, and the actual struct that I'm passing into it has quite a bit more fields than 2.– Typhaon Nov 02 '22 at 09:39