Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

swapping an inner and outer vector

I have a vector of vector of myObjects defined, creating essentially a 2D array. I would like to transpose this array such that rows become columns and columns become rows. Obviously I could do this in a double for-loop, but this seems massively inelegant and will be pretty slow. I was wondering if there's something clever in C++ or the STL that would let me swap the inner and outer vectors around quickly and efficiently, rather than writing...

for (int iRow = 0; iRow < nRows; ++iRow)
{
      for (int iCol = 0; iCol < nCols; ++iCol)
      {
         myNew2DArray[iCol][iRow] = myOriginal2DArray[iRow][iCol];
      }
}
like image 562
Dave Heath Avatar asked Mar 13 '26 19:03

Dave Heath


1 Answers

Alternatively, you can store the matrix in a vector and have a flag that specifies whether the matrix is transposed or not. Then you simply calculate the index. Here is an example:

class Matrix {
private:
    std::vector<int> matrix;
    bool isTransposed = false;
    int width, height;

public:
    // ...

    int getElement(int x, int y)
    {
        int w = width;
        int h = height;

        if(isTransposed) {
            int z = x;
            x = y;
            y = x;

            z = w;
            w = h;
            h = z;
        }

        return matrix[y * width + x];
    }

    // ...
};

This will reduce the cost of transposing the matrix, but increases the cost of actually accessing the elements.

like image 153
npclaudiu Avatar answered Mar 16 '26 10:03

npclaudiu