Search code examples
c++classvectordynamic-memory-allocation

Private member vector of vector dynamic memory allocation


I'm new to C++ (I learned programming with Fortran), and I would like to allocate dynamically the memory for a multidimensional table. This table is a private member variable :

class theclass{
public:
  void setdim(void);
private:
  std::vector < std::vector <int> > thetable;
}

I would like to set the dimension of thetable with the function setdim().

void theclass::setdim(void){
  this->thetable.assign(1000,std::vector <int> (2000));
}

I have no problem compiling this program, but as I execute it, I've got a segmentation fault.

The strange thing for me is that this piece (see under) of code does exactly what I want, except that it doesn't uses the private member variable of my class :

std::vector < std::vector < int > > thetable;
thetable.assign(1000,std::vector <int> (2000));

By the way, I have no trouble if thetable is a 1D vector. In theclass :

std::vector < int > thetable;

and if in setdim :

this->thetable.assign(1000,2);

So my question is : why is there such a difference with "assign" between thetable and this->thetable for a 2D vector? And how should I do to do what I want?

Thank-you for your help,

Best regards,

-- Geoffroy


Solution

  • Thank you everybody for your comments. I was on the way to do a small source code with only the problematic part, and as I tried to run it, it worked... I was very confused so I tried to find the differences between the instructions. Finally, I figured out that I forgot a

    #include <vector>
    

    in one of the source file (the main one, but not the one with the class definition). This is strange to me because without it, I don't understand how it can compile... So this should be an other question, but I still don't understand where to put these #include... Life was easier with Fortran ;-)

    Thank you again,

    -- Geoffroy