Simpler way to set multiple array slots to one value

前端 未结 10 2252
我寻月下人不归
我寻月下人不归 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条回答
  •  -上瘾入骨i
    2021-02-18 17:06

    I just had a play around for the sake of fun / experimentation (Note my concerns at the bottom of the answer):

    It's used like this:

    smartAssign(array)[0][8]       = 1;
    smartAssign(array)[1][4][2]    = 2;
    smartAssign(array)[3]          = 3;
    smartAssign(array)[5][9][6][7] = 4;
    

    Source code:

    #include  //Needed to test variables
    #include 
    #include 
    
    template 
    class SmartAssign
    {
        ArrayPtr m_array;
    
    public:
        class Proxy
        {
            ArrayPtr m_array;
            size_t m_index;
            Proxy* m_prev;
    
            Proxy(ArrayPtr array, size_t index)
                : m_array(array)
                , m_index(index)
                , m_prev(nullptr)
            { }
    
            Proxy(Proxy* prev, size_t index)
                : m_array(prev->m_array)
                , m_index(index)
                , m_prev(prev)
            { }
    
            void assign(Value value)
            {
                m_array[m_index] = value;            
                for (auto prev = m_prev; prev; prev = prev->m_prev) {
                    m_array[prev->m_index] = value;
                }
            }
    
        public:
            void operator=(Value value)
            {
                assign(value);
            }
    
            Proxy operator[](size_t index)
            {
              return Proxy{this, index};
            }
    
            friend class SmartAssign;
        };
    
        SmartAssign(ArrayPtr array)
            : m_array(array)
        {
        }
    
    
        Proxy operator[](size_t index)
        {
            return Proxy{m_array, index};
        }
    };
    
    template 
    SmartAssign smartAssign(T* array)
    {
        return SmartAssign(array);
    }
    
    int main()
    {
        int array[10];
    
        smartAssign(array)[0][8]       = 1;
        smartAssign(array)[1][4][2]    = 2;
        smartAssign(array)[3]          = 3;
        smartAssign(array)[5][9][6][7] = 4;
    
        for (auto i : array) {
            std::cout << i << "\n";
        }
    
        //Now to test the variables
        assert(array[0] == 1 && array[8] == 1);
        assert(array[1] == 2 && array[4] == 2 && array[2] == 2);
        assert(array[3] == 3);
        assert(array[5] == 4 && array[9] == 4 && array[6] == 4 && array[7] == 4);
    }
    

    Let me know what you think, I don't typically write much code like this, I'm sure someone will point out some problems somewhere ;)

    I'm not a 100% certain of the lifetime of the proxy objects.

提交回复
热议问题