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?
            Asked
            
        
        
            Active
            
        
            Viewed 170 times
        
    3
            
            
         
    
    
        econ
        
- 495
- 3
- 6
- 16
- 
                    Possible duplicate of [Initialization of a normal array with one default value](https://stackoverflow.com/questions/1065774/initialization-of-a-normal-array-with-one-default-value) – Sep 12 '17 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. – Jarod42 Sep 12 '17 at 17:20
- 
                    `std::vectorv(300,10);` – Sep 12 '17 at 17:22
2 Answers
8
            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);
 
    
    
        Simple
        
- 13,992
- 2
- 47
- 47
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
 
    
    
        Phydeaux
        
- 2,795
- 3
- 17
- 35
- 
                    1Note, this doesn't *initialize* a fixed array, it fills via *assignment*. – WhozCraig Sep 12 '17 at 17:09
- 
                    It also isn’t `constexpr`, so you can’t use it at compile time to get the same effect. – Daniel H Sep 12 '17 at 17:11