静态声明的二维数组 C++ 作为类的数据成员 [英] Statically declared 2-D array C++ as data member of a class
问题描述
我正在尝试创建一个 class grid
,其中包含数据成员 unsigned NR
、unsigned NC
并且它还应该包含一个二维数组双坐标[NR][NC]
.我希望通过类构造函数初始化数据成员 NR
和 NC
.我试图避免二维数组的动态分配,因为我更喜欢连续的内存分配,以便尽可能避免缓存未命中.
I am trying to create a class grid
which contains the data members unsigned NR
, unsigned NC
and it should also contain a 2D array double Coordiantes[NR][NC]
. I wish to initialize the data members NR
and NC
through the class constructor. I am trying to avoid the dynamic allocation of the 2-D array as I prefer contiguous memory allocation so as to avoid the cache misses as much as possible.
我不确定是否可行,但任何输入都会有所帮助.
推荐答案
class Array2D {
public:
vector<int> v;
int nc;
Array2D(int NR, int NC) : v(NR*NC), nc(NC) {}
int* operator[](int r) { return &v[r*nc]; }
};
int main()
{
Array2D array2d(2, 3);
array2d[0][0] = 1;
array2d[1][2] = 6;
}
这允许您创建一个功能类似于二维数组的类.速度很快,而且数据是连续的.
This allows you to create a class that will function like a 2D array. It's fast and the data is contiguous.
这篇关于静态声明的二维数组 C++ 作为类的数据成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!