nostyn
nostyn

Reputation: 19

How to initialize a vector

If to use the vector I use:

std::vector<class> obj(size);

And together with the initializer list:

std::vector<class> obj; 
MyClass::MyClass():obj(size)

If I wanted to enter "obj(size)" Outside the initializer list, what is the syntax? (For example, to create within a separate function)

Upvotes: 0

Views: 76

Answers (1)

birdfreeyahoo
birdfreeyahoo

Reputation: 445

Since the vector is initialized with a default size when it is constructed, you have to resize it. You can use the following code:

obj.resize(size);

Keep in mind that this operation can be expensive, so don't use it too often. If you add more elements to the vector than it can hold, it automatically resizes.

If you need more information just visit the vector documentation here.

Upvotes: 1

Related Questions