带有2D数组的C 宏
C++ macro with 2D array
我正在使用: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
相关文章:
- 2D数组来自文本输入,中间有空格
- 如何使用用户输入在C++中正确填充2D数组
- 如何在C++中检查2D数组中负值的输入验证
- 当我在main中声明了我的2d数组时,为什么我的程序会退出
- 如何将以逗号和空格分隔的整数读取到 2D 数组中?
- 如何在C++函数中声明静态 2D 数组?
- 如何声明一个可以在整个程序中使用的全局 2d 3d 4d .. 数组(堆版本)变量?
- 我已经阅读了很多关于 2d 数组的信息,但我在作业中使用它时遇到了麻烦
- 使用矢量将文本文件中的输入存储到 2D 数组中
- 获取 2D 数组 c++ 中的所有数字对
- 这是使用回溯的 nqueen 问题,但我使用了动态 2d 数组,我的程序编译良好,但不返回任何输出
- 如何在构造函数中使用初始值设定项设置具有相同值的 2d 数组?
- 在 Python 和 c++ 2d 数组初始化之间.这是怎麽?为什么呢?
- 如何打印 2D 字符数组C++
- 如何将数组 2d 作为参数从函数传递并返回数组 2d 此函数
- 数组 2D 多个值
- 创建数组数组 (2D),而无需在 Java 中初始化内部数组
- 如何在C++中将文本文件传输到数组2D
- 从同一类的另一个方法调用数组2D-C++
- 获取地址在数组2d中的位置