1

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()); } 
0

3 Answers 3

7

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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); 

Comments

1

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());

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.