Normally if I for example have string array[10]
I can initialize all spots in the array like:
for(int i = 0; i < 10; i++)
array[i] = "";
or if it is an array with pointers I write array[i] = nullptr
instead, but how do I initialize when the type is more general like T array[10]
?
If value-initialization is all you need, then you can value-initialize all array members with empty braces:
T array[10]{};
// ^^
Or:
T array[10] = {};
Value-initialization produces the zero or null value for scalars, value-initializes each member for aggregates, and calls the default constructor for non-aggregate class types.
(If you want to initialize your array elements with values other than T{}
, then you need something more complex and specific.)
Well you could do like the standard does and use an initialization function in the form of
template<typename T, std::size_t N>
void initialize(T (&arr)[N], const T& value = T())
{
for(auto& e : arr)
e = value;
}
Now you can call this and not pass a value and the array with be initialized with default value or you can specify a value and the array will be initialized with that value.
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