Simpler way to set multiple array slots to one value

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

    Compilers which still doesn't support variadic template argument and universal initialization list, it can be a pain to realize, that some of the posted solution will not work

    As it seems, OP only intends to work with arrays of numbers, valarray with variable arguments can actually solve this problem quite easily.

    #include      
    #include 
    #include 
    #include 
    #include 
    template 
    std::valarray  selection( ... )
    {
        va_list arguments; 
        std::valarray sel(size);   
        //Skip the first element
        va_start ( arguments, size );
        va_arg ( arguments, int );
        for(auto &elem : sel)
            elem = va_arg ( arguments, int );
        va_end ( arguments );
        return sel;
    
    }
    int main ()
    {
        //Create an array of 30 integers
        std::valarray array(30);
        //The first argument is the count of indexes
        //followed by the indexes of the array to initialize
        array[selection<3>(9,5,14)] = 1;
        array[selection<4>(8,15,13, 12)] = 2;
        std::copy(std::begin(array), std::end(array),
                  std::ostream_iterator(std::cout, " "));
        return 0;
    }
    

提交回复
热议问题