你将如何使用二维来处理一维内存

How would you address one dimensional memory using two dimensions?

本文关键字:二维 处理 一维 内存 何使用      更新时间:2023-10-16

如何使用二维来寻址一维内存?(例如获得值Matrix::ValueAt(row, col),其中Matrix将值存储为一维阵列(对于4x4矩阵为float m[16])。

class Matrix4x4
{
    private float m[16];
    float getValueAt(int row, int col)
    {
        // I want this function
    }
}

使用m[row * 4 + col],或者相反。

让编译器弄清楚:

class Matrix4x4
{
private:
    union
    {
        float m[16];
        float m2[4][4];
    };
public:
    float getValueAt(int row, int col)    
    {
        return m2[row][col];
    }
    float getValueAtLinear(int i)    
    {
        return m[i];
    } 
}

一般情况下:

矩阵(i,j)=m[i*列+j]