John smith
John smith

Reputation: 27

Problems Initializing Vector

I'm new to c++ so I'm kind of consfused I wanted to do something like that:

`

 int max = 30;

    class MyClass{
     vector<int> data(max);
    };

but it wasn't working, because it was not recognizing that "max" was that int I had just initialized. so i changed to that:

class MyClass{
     MyClass();
     int max;
     vector<int> data(max);
    }
MyClass::MyClass(){
  max = 40;}

Don't work unless I initialize the vector in the constructor, but I don't know the correct sintax.

How can I make this work? All I want is to initialize "max" and then use it as the initial size of the vector.

Upvotes: 0

Views: 124

Answers (1)

Jerry Coffin
Jerry Coffin

Reputation: 490018

You prof/teacher should have told you about initializer lists. The syntax looks something like this:

class MyClass {
    std::vector<int> data;
public:
    MyClass(int max) : data(max) { }
};

Upvotes: 1

Related Questions