gpt4 book ai didi

带有二维数组的 C++ 宏

转载 作者:行者123 更新时间:2023-11-30 05:19:20 25 4
gpt4 key购买 nike

我正在使用:Windows 10、C++、Visual Studio 2013。

我正在寻找一种方法来访问带有负数的二维数组,例如我知道这适用于一维数组:

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

最佳答案

您可以对二维数组使用相同的方法,因为 define 可能有参数:

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

关于带有二维数组的 C++ 宏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41183832/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com