c++ - 作为类成员的 2D vector 指针

标签 c++ class pointers vector

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

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

最佳答案

你应该通过 v作为引用而不是复制。

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

必须确保您的vector<vector<float>>比你的 Vectorref 长寿,否则你会再次遇到段错误。

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

关于c++ - 作为类成员的 2D vector 指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43200916/

相关文章:

c - 左值需要作为一元 ‘&’ 操作数

java - 对java中的内存感到困惑

c++ - 是否可以实现 [] 运算符两次?

c++ - 对象的定义和实例化

Python:如何在创建时向父类注册所有子类

c++ - 缓冲区刷新: "\n"与 std::endl

pointers - 分配 block 指针: differences between Objective-C vs C++ classes

c++ - 使用 gdb 调试 LLVM 检查器时如何以图形方式查看 CFG

c++ - 运行时切换选择

c++ - 在运行时根据实例变量转换对象 (C++)