dafsd
dafsd

Reputation: 55

Initializing vectors in C++?

I have a variable called vector_size. The value of this variable is inputted by the user at run time. I also have a class MyClass.

I want to create a vector of MyClass. I want the vector to have vector_size elements. How would I do this?

This is what I've tried so far:

vector <MyClass> myVector (vector_size) = MyClass();

The code above doesn't work. How would I make a vector of vector_size, and each element is initialized?

Note that I do not want to just "reserve space" for vector_size elements. I want the vector to be populated with vector_size elements, and each element needs to be initialized with the constructor.

Essentially, I want to do the following in one line:

vector <MyClass> myVector;
for (int counter = 0; counter < vector_size; counter++) {
    myVector.pushBack (MyClass());
}

Upvotes: 1

Views: 139

Answers (3)

Florian Prud&#39;homme
Florian Prud&#39;homme

Reputation: 599

MyClass should have either a default Constructor, or a Constructor which does not take any parameter to do what you want.

Then you can call :

vector <MyClass> myVector (vector_size);

Upvotes: 2

bialpio
bialpio

Reputation: 1024

The way to go is:

vector<MyClass> myVector(size, MyClass());

This should also work:

vector<MyClass> myVector(size);

The first variant takes an object that will be used to construct the elements of the vector, the second one will initialize them using default constructor, so in this case both variants should be equivalent.

Upvotes: 7

yasouser
yasouser

Reputation: 5177

Look at std::vector<int> second in the example here: http://www.cplusplus.com/reference/vector/vector/vector/

While you are there look at the "fill constructor" for std::vector.

For your case: std::vector<MyClass> v(vector_size, MyClass());

Upvotes: 1

Related Questions