作为类的数据成员

作为类的数据成员

本文介绍了静态声明的2-D数组C ++作为类的数据成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图创建一个类网格,其中包含数据成员 unsigned NR unsigned NC ,它还应包含一个二维数组 double Coordiantes [NR] [NC] 。我想通过类构造函数初始化数据成员 NR NC 。我试图避免2-D数组的动态分配,因为我喜欢连续的内存分配,以尽可能避免缓存缺失。

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.

我不知道是否可能,但任何输入都会有帮助。

I am not sure if it is possible but any inputs would be helpful.

推荐答案

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;
}

这允许你创建一个类似2D数组的类。速度快,数据连续。

This allows you to create a class that will function like a 2D array. It's fast and the data is contiguous.

这篇关于静态声明的2-D数组C ++作为类的数据成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 14:40