【问题标题】:2D Vector pointer as member of class作为类成员的二维向量指针
【发布时间】:2017-04-04 07:31:14
【问题描述】:

我是 C++ 新手。 我正在尝试制作一个由 2d 矢量指针组成的类。我正在创建一个将二维向量作为参数的对象。我正在尝试使用指针来引用这个 2D 向量。这编译得很好,但我在执行时遇到了分段错误。 我在这里附上我的代码。请帮忙!

# include <iostream>
# include <vector>
using namespace std;

class Vectorref {
        vector<vector<float> >  *vptr; // pointer to 2D vector

    public:
        Vectorref(vector<vector<float> >);
        double getval(int,int);
};

Vectorref::Vectorref(vector<vector<float> > v)
{
    vptr = &v;
}

double Vectorref::getval(int r, int c)
{
    return (*vptr)[r][c];
}

int main(){
    vector<vector<float> > A (3,vector<float>(3,2.0));

    Vectorref B(A);

    for(int i=0; i<3 ;i++){
        for(int j=0; j<3; j++){
            cout << B.getval(i,j) << "\t";
        }
        cout << endl;
    }

    return 0;
}

【问题讨论】:

  • vptr = &amp;v; - v 是一个自动变量;传递参数的副本。您正在保存一个自动变量的地址,该地址将在构造函数退出范围时不复存在。
  • @WhozCraig 那我该怎么办?

标签: c++ class pointers vector


【解决方案1】:

您应该传递v 作为参考而不是复制。

Vectorref(vector<vector<float> >&);
Vectorref::Vectorref(vector<vector<float> >& v)

必须确保您的 vector&lt;vector&lt;float&gt;&gt; 比您的 Vectorref 寿命更长,否则您将再次遇到分段错误。

您的getval 函数应返回float 而不是double

【讨论】:

  • 我知道它的基本问题,但我想问的是,在这段代码中,只有p 向量在占用内存,对吧?指向和引用不会创建任何会占用内存的副本?
  • 来自您的原始示例。变量vector&lt;vector&lt;float&gt; &gt; A 将占用最多的内存。另一个变量 Vectorref B 只需要 sizeof(vector&lt;vector&lt;float&gt;&gt;*) == sizeof(size_t) 字节,在 64 位机器上是 8 个字节。
猜你喜欢
  • 1970-01-01
  • 2018-03-24
  • 1970-01-01
  • 1970-01-01
  • 2015-02-15
  • 1970-01-01
  • 1970-01-01
  • 2019-01-16
  • 2013-02-15
相关资源
最近更新 更多