Is there shortcut to initialize fixed size array with constants. For examle, it I need int array[300] with 10 in each of 300 spaces, is there trick to avoid writinig 10 300 times?
2 Answers
Here's a compile time solution that uses initialisation (uses std::array instead of a C array):
template<std::size_t N, typename T, std::size_t... Is>
constexpr std::array<T, N> make_filled_array(
std::index_sequence<Is...>,
T const& value
)
{
return {((void)Is, value)...};
}
template<std::size_t N, typename T>
constexpr std::array<T, N> make_filled_array(T const& value)
{
return make_filled_array<N>(std::make_index_sequence<N>(), value);
}
auto xs = make_filled_array<300, int>(10);
auto ys = make_filled_array<300>(10);
1 Comment
Jarod42
You may reverse order of template parameter to allow
T deduction.You can use std::fill_n:
int array[300] = {0}; // initialise the array with all 0's
std::fill_n(array, 300, 10); // fill the array with 10's
std::array, you could implement something to have that array initialized that way, for C-array, simpler would be to fill it.std::vector<int> v(300,10);