How to initialize all elements in an array to the same number in C++

后端 未结 16 1998
伪装坚强ぢ
伪装坚强ぢ 2020-12-05 07:17

I\'m trying to initialize an int array with everything set at -1.

I tried the following, but it doesn\'t work. It only sets the first value at -1.

in         


        
16条回答
  •  青春惊慌失措
    2020-12-05 08:00

    If you are allowed to use std::array, you can do the following:

    #include 
    #include 
    #include 
    using namespace std;
    
    template 
    struct S_internal {
        template 
        static array init_array() {
            return S_internal::init_array();
        }
    };
    
    template 
    struct S_internal {
        template 
        static array init_array() {
            static_assert(S == sizeof...(values), "");
            return array {{values...}};
        }
    };
    
    template 
    struct init_array
    {
        static array get() {
            return S_internal::init_array<>();
        }
    };
    
    void main()
    {
        array ss = init_array::get();
        copy(cbegin(ss), cend(ss), ostream_iterator(cout, " "));
    }
    

    The output is:

    77 77 77 77 77

提交回复
热议问题