在类中声明动态2D向量 [英] Declaring Dynamic 2D Vector in class

查看:109
本文介绍了在类中声明动态2D向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们试图使用2D向量,因为我们想要一个动态增长的二维数组。

We're trying to use a 2D vector because we want a 2D array that will grow dynamically.

我们尝试过:
在类声明:

We tried this: In the class declaration:

    vector<vector<double> > table;

但是表似乎没有被分配。

But then table doesn't seem to be allocated. We get a segfault when we try to access members.

然后我们尝试了:

类别声明:

    vector<vector<double> >* table;

构造函数:

     table = new vector<vector<double> >;

但现在我们以前访问它的方式(使用[] [])不工作。

But now we the way we accessed it before (with [][]) doesn't work.

我们尝试了一个有这个类的虚拟类:

We tried a dummy class with this:

class myClass {
    public:
    myClass();
    ~myClass();
    vector<vector<double> > t;
 };

myClass::myClass() 
{
    t = vector<vector<double> > (10, vector<double>(10));
}

但它不会正常释放,我们得到核心转储。此外,当我们试图增长数组时,我们将expclitly构造每个新行。

But it wouldn't free properly and we got core dumps. Also when we tried to grow the array, we'd have expclitly construct each new row.

例如:

t[50] = vector<double>(5);
t[50][10] = 10;

如果我们不这样做,我们会得到一个segfault

If we didn't do it like this, we'd get a segfault

推荐答案

您需要在访问元素之前调整表格大小。

You'll need to resize the tables before you access elements.

vector<vector<double> > table;
table.resize(10);
for (int i = 0; i < 10; ++i)
  table[i].resize(20);

这篇关于在类中声明动态2D向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆