C++ 2D Vector got error

2019-09-19 11:38发布

问题:

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

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

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".

回答1:

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
{
}


回答2:

Suggestion: I can't help thinking that it would be a bit simpler (and possibly internally more compact) if you just stored this internally as one vector rather than a vector of vectors. I.e.

std::vector<double> m;
size_t x;
size_t y;

This might not seem two dimensional but remember that this is a private detail of your class and that's what encapsulation is for.

I think the problem you're getting here though is that you're trying to deference the vector(s) before having sized them. When you create a vector you either have to give it an initial size, or you push values back on to it to increase the size. You probably want to do the former which you could do with:

void matrix::resize( size_t x1, size_t y1 )
{
    m.clear();
    x = x1;
    y = y1;
    m.resize( x * y );
}

You can then access an individual element of the matrix using:

double matrix::get( size_t x1, size_t y1 )
{
    return m[ x1 * x + y1 ];
}


回答3:

Basically, what you're doing in the constructor is

vector<vector<int> > m(size, vector<int>(size));

m is a local variable here. Hence, it is not available outside the constructor, and hence in the func(), you are basically trying to access an uninitialised vector.

To fix this, initialise m in the constructor by changing the above statement to:

m = vector<vector<int> >(size, vector<int>(size));


标签: c++ c++11 vector