Simpler way to set multiple array slots to one value

前端 未结 10 2254
我寻月下人不归
我寻月下人不归 2021-02-18 16:31

I\'m coding in C++, and I have the following code:

int array[30];
array[9] = 1;
array[5] = 1;
array[14] = 1;

array[8] = 2;
array[15] = 2;
array[23] = 2;
array[1         


        
10条回答
  •  误落风尘
    2021-02-18 17:02

    Use overload operator << .

    #include 
    #include 
    #include 
    
    // value and indexes wrapper
    template< typename T,  std::size_t ... Ints> struct _s{ T value; };
    
    //deduced value type
    template< std::size_t ... Ints,  typename T>
    constexpr inline   _s  _ ( T const& v )noexcept { return {v}; }
    
    
    // stored array reference
    template< typename T, std::size_t N>
    struct _ref
    {
        using array_ref = T (&)[N];
    
        array_ref ref;
    };
    
    
    //join _s and _ref with << operator.
    template< 
            template< typename , std::size_t ... > class IC, 
            typename U, std::size_t N, std::size_t ... indexes
            >
    constexpr _ref operator << (_ref r, IC ic ) noexcept
    {
        using list = bool[];
        return (  (void)list{ false, (  (void)(r.ref[indexes] = ic.value), false) ... }) , r ;
    
        //return r;
    }
    
    
    //helper function, for creating _ref from array.
    template< typename T, std::size_t N>
    constexpr inline _ref _i(T (&array)[N] ) noexcept { return {array}; }
    
    
    
    int main()
    {
    
       int a[15] = {0};
    
       _i(a) << _<0,3,4,5>(7) << _<8,9, 14>( 6 ) ;
    
    
       for(auto x : a)std::cout << x << "  " ;  
       //       0  1  2  3  4  5  6  7  8  9 10 11 12 13 14
      //result: 7  0  0  7  7  7  0  0  6  6  0  0  0  0  6
    
    
      double b[101]{0};
    
      _i(b) << _<0,10,20,30,40,50,60,70,80,90>(3.14) 
            << _<11,21,22,23,24,25>(2.71) 
            << _<5,15,25,45,95>(1.414) ;
    }
    

提交回复
热议问题