带有2D数组的C 宏

C++ macro with 2D array

本文关键字:数组 2D 带有      更新时间:2023-10-16

我正在使用:Windows 10,C ,Visual Studio2013。

我正在寻找一种访问带负数的2D阵列的方法,例如,我知道这与1D阵列一起使用:

int myarray[35];
#define a (myarray + 50)
a[-45] = 0; //accesses myarray[5]

,但无法弄清楚如何使其与2D阵列一起使用:

int foo[32][32]
#define bar (foo + 50)(foo + 50)
// The above does not work

您可以使用与 define s相同的方法使用相同的方法:

int a[100][100];
#define b(x,y) a[x + 50][y + 50]
a[0][0] = 123;
cout << b(-50, -50) << endl; // prints 123

我个人不想使用此define驱动的方法,因为这限制了您可以在数组上执行的操作(例如,您不能写b(1)表示一个特定的行a[51]或必须为其定义另一个宏)。

要提高可读性和可维护性,请根据std::vector考虑编写自己的课程:

template<typename T>
class ShiftedVector {
private:
    int shift;
    std::vector<T> storage;
public:
    T& operator[] (int idx) {
        return storage[idx + shift];
    }
    // Definitions of other useful operations
}
ShiftedVector<ShiftedVector<int>> x; // Usage