C ++ 2D向量得到错误 [英] C++ 2D Vector got error

查看:149
本文介绍了C ++ 2D向量得到错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



我想创建一个2D维向量而不是使用数组。但是,我有一个运行时错误。

I want to create a 2D dimensional vector rather using array. However, I got a runtime error.

我创建一个向量< vector< int& > m(size,vector< int>(size))以确保向量中的所有元素都等于零,并且我通过了test1。我不能通过test2,我评论失败。

I create a vector<vector<int> > m(size, vector<int>(size)) to make sure all elements in vector are equal to zero, and I passed the test1. I can't pass test2 on which I commented "failure".

推荐答案

在您的构造函数中,您正在创建一个局部变量 m 用它。当然,在 func 函数中不可用。为了使它工作,你需要初始化对象的成员变量 m 。此外,您在构造函数中创建的向量是错误类型( int ,而不是 double

Inside your constructor you are creating a local variable m, and use it. It is, of course, not available in the func function. To make it work, you instead need to initialize the object's member variable m. Furthermore, the vector you are creating in the constructor is of a wrong type (int instead of double)

matrix::matrix(int size)
    : m(size, vector<double>(size)) //initializing the vector
{
}

这篇关于C ++ 2D向量得到错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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