#include <string>
#include <iostream>
#include <vector>
#include <iomanip>
using namespace std;
class matrix
{
public:
matrix(int);
void func(int);
vector<vector<double> > m;
};
matrix::matrix(int size)
{
//set 3 X 3 = 9 elements to zero
vector<vector<int> > m(size, vector<int>(size));
// success
cout << "test1 if m[0][0] equals to zero: " << m[0][0] << endl;
}
void matrix::func(int size)
{
// failure, can't pass till here
cout << "test2 if m[0][0] equals to zero: " << m[0][0] << endl;
for(int i = 1; i != size; ++i)
{
m[i][i] = 0;
}
}
int main()
{
int input1 = 3;
matrix mat(input1);
mat.func(input1);
}
Run Code Online (Sandbox Code Playgroud)
我想创建一个2D维向量而不是使用数组.但是,我遇到了运行时错误.
我创建一个vector<vector<int> > m(size, vector<int>(size))以确保向量中的所有元素都等于零,并且我通过了test1.我无法通过我评论过"失败"的test2.
在构造函数中,您将创建一个局部变量m,并使用它.当然,它在func功能中不可用.为了使其工作,您需要初始化对象的成员变量m.此外,您在构造函数中创建的向量是错误的类型(int而不是double)
matrix::matrix(int size)
: m(size, vector<double>(size)) //initializing the vector
{
}
Run Code Online (Sandbox Code Playgroud)