3

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?

3
  • Possible duplicate of Initialization of a normal array with one default value Commented Sep 12, 2017 at 17:15
  • With std::array, you could implement something to have that array initialized that way, for C-array, simpler would be to fill it. Commented Sep 12, 2017 at 17:20
  • std::vector<int> v(300,10); Commented Sep 12, 2017 at 17:22

2 Answers 2

7

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);
Sign up to request clarification or add additional context in comments.

1 Comment

You may reverse order of template parameter to allow T deduction.
6

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

2 Comments

Note, this doesn't initialize a fixed array, it fills via assignment.
It also isn’t constexpr, so you can’t use it at compile time to get the same effect.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.