Simpler way to set multiple array slots to one value

前端 未结 10 2215
我寻月下人不归
我寻月下人不归 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 16:48

    struct _i_t
    {
        int * array;
    
    
        struct s
        {
            int* array;
            std::initializer_list l;
    
            s const&   operator = (int value) const noexcept
            {
                for(auto i : l )
                  array[i] = value;
    
                return *this;
            }
        };
    
        s operator []( std::initializer_list i ) const noexcept
        {
            return s{array, i};
        }
    };
    
    template< std::size_t N>
    constexpr _i_t   _i( int(&array)[N]) noexcept { return {array}; }
    
    int main()
    {
      int a[15] = {0};
      _i(a)[{1,3,5,7,9}] =  7;
    
      for(auto x : a)std::cout << x << ' ';
    
    
    }
    

提交回复
热议问题