Search code examples
c++initializationstdarray

Initializing a std::array with all elements having the same value


I need to initialize all elements of a std::array with a constant value, like it can be done with std::vector.

#include <vector>
#include <array>

int main()
{
  std::vector<int> v(10, 7);    // OK
  std::array<int, 10> a(7);     // does not compile, pretty frustrating
}

Is there a way to do this elegantly?

Right now I'm using this:

std::array<int, 10> a;
for (auto & v : a)
  v = 7;

but I'd like to avoid using explicit code for the initialisation.


Solution

  • 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 types.