How to rewrite array from row-order to column-order?

后端 未结 5 1807
遥遥无期
遥遥无期 2020-12-31 16:33

I have this double for-loop, where I have both row-order and column-order array indexing, which should be bad for performance.

  for (int row = 0; row < h         


        
5条回答
  •  死守一世寂寞
    2020-12-31 17:10

    If swapping the row orrdering is common then write your own array class.

    The data does not actually have to move just the interface that accesses the data needs to know how to access the data.

    #include 
    class Matrix
    {
      public:
        Matrix(int width,int height)
            :data(width,std::vector(height))
            ,rowOrder(true)
        {
        }
        int& operator()(int x,int y)
        {
            return at(x,y);
        }
        int const& operator()(int x,int y) const
        {
            return const_cast(*this).at(x,y);
        }
    
        void switchRowOrder()
        {
            rowOrder = !rowOrder;
        }
    
      private:
        int& at(int x,int y)
        {
            int& result = (rowOrder)
                                ?data[x][y]  // row Order Access
                                :data[y][x]; // col Order Access
    
            // Note there is no code to swap around the content of the data internally.
            return result;
        }
    
        std::vector >  data;
        bool rowOrder;
    };
    

提交回复
热议问题