0

Normally I would define a new array and vector with size n in C++ like this:

int* xArray = new int[n];
vector<int> yVector(n);

But now I have a class Maze which has a header. The arrays and vectors are supposed to be declared in the header and then allocated in f.ex. the constructor.

The arrays are declared in Maze.h like this:

class Maze {
public:
    int* xArray;
}

And then allocated in Maze.cpp like this:

xArray = new int[n];

Now I can use xArray from any function in the class Maze.

But what is the equivalent way to declare and allocate vectors? This is what I tried:

In Maze.h:

class Maze {
public:
    vector<int> yVector;
}

In Maze.cpp:

yVector(n);

But when compiling I get:

error: no match for call to ‘(std::vector<int>) (int)’
 yVector(n);

So does it think that yVector is a function, and that I am trying to call the function? I tried to specify that this is a class field by writing this->yVector(n); instead, but that made no difference.

Next I tried putting vector<int> yVector(n); in the constructor. It compiles. But when I later try to use yVector[0] in another function I get Segmentation fault (core dumped), so I guess all I did was declare a new, local vector, which is not what I wanted.

So how am I supposed to define class vectors when using a header file?

PaulMag
  • 3,928
  • 3
  • 18
  • 29

1 Answers1

1

Maybe what you're looking for is std::vector::reserve. Note that you still need to push_back elements into the vector after doing reserve. It only makes sure that the capacity is enough to store requested number of elements.

Or, alternatively you can create a new vector in your constructor and copy it to the member.

vector<int> temp_vec(n);
yVector = temp_vec;
nishantsingh
  • 4,537
  • 5
  • 25
  • 51