Как инициализировать одномерный массив без цикла?

Я хочу инициализировать массив единицами, но инициализирует только одно значение единицей остальное нулями.

я делаю так

int size = 5;
int array_asfkf[size]{1};

знаю можно через цикл вот так

int size = 5;
int array_asfkf[size]{};
for (int i = 0; i < size; ++i) {
            array_asfkf[i] = 1;
        }

Но хочется что то упрощенное.


Ответы (1 шт):

Автор решения: user7860670
#include <array>
#include <utility>
#include <cstddef>

template<::std::size_t x_size, ::std::size_t... x_indexes>
[[nodiscard]] auto
Make_Array_Impl(int const value, ::std::index_sequence<x_indexes...>)
{
    return ::std::array<int, x_size>{(static_cast<void>(x_indexes), value) ...};
}

template<::std::size_t x_size>
[[nodiscard]] auto
Make_Array(int const value)
{
    return Make_Array_Impl<x_size>(value, ::std::make_index_sequence<x_size>());
}

#include <cassert>

int main()
{
    auto const items{Make_Array<3>(1)};
    assert(1 == items[0]);
    assert(1 == items[1]);
    assert(1 == items[2]);
    return 0;
}

online compiler

→ Ссылка