Initializing a std::array with a constant value
With std::index_sequence
, you might do:
namespace detail
{
template <typename T, std::size_t ... Is>
constexpr std::array<T, sizeof...(Is)>
create_array(T value, std::index_sequence<Is...>)
{
// cast Is to void to remove the warning: unused value
return {{(static_cast<void>(Is), value)...}};
}
}
template <std::size_t N, typename T>
constexpr std::array<T, N> create_array(const T& value)
{
return detail::create_array(value, std::make_index_sequence<N>());
}
With usage
auto a = create_array<10 /*, int*/>(7); // auto is std::array<int, 10>
Which, contrary to std::fill
solution, handle non default constructible type.
Alas not; std::array
supports aggregate initialisation but that's not enough here.
Fortunately you can use std::fill
, or even std::array<T,N>::fill
, which, from C++20 is elegant as the latter becomes constexpr
.
Reference: https://en.cppreference.com/w/cpp/container/array/fill
You can do as following
std::array<int, 10> a;
a.fill(2/*or any other value*/);
Or use std::fill
from algorithms header file.
To include algorithms header file use
#include <algorithm>