简体   繁体   中英

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM