2016-12-16 39 views
1

我使用:的Windows 10,C++,Visual Studio的2013年C++宏观与二维数组

我正在寻找一种方式来访问我的二维数组负数,比如我知道这工作有一维数组:

int myarray[35]; 

#define a (myarray + 50) 

a[-45] = 0; //accesses myarray[5] 

,但无法弄清楚如何使它具有二维阵列工作:

int foo[32][32] 

#define bar (foo + 50)(foo + 50) 

// The above does not work 
+0

这不会使一吨的感觉。即使你使用1D数组,如果你访问'a [-5]',你已经做了一个越界请求。 –

+0

为什么会-45给你第5项?这没有任何意义。 – Lundin

+1

由于在上面的行定义..它的作品.. –

回答

1

你可以使用二维数组,一样的方法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