econ
econ

Reputation: 525

Array initialization with identical elements

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?

Upvotes: 3

Views: 405

Answers (2)

Simple
Simple

Reputation: 14390

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);

Upvotes: 7

Phydeaux
Phydeaux

Reputation: 2855

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

Upvotes: 6

Related Questions