Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing some elements of vector of defined size

Tags:

c++

vector

Is there a way to initialize first few elements of a vector after defining the size of the vector like -

vector<int> vec (10);

This doesn't work and produces a compiler error -

vector<int> vec(10) {1,2,3};

For example with arrays we can do the same thing like -

int arr[5] {1,2,3}; // This will initialize the first 3 elements of the array to 1,2,3 and the remaining two to 0.
like image 383
stormbreaker Avatar asked Sep 02 '25 03:09

stormbreaker


1 Answers

In short, no. Your can fill out the entire list of things you want to be in the vector:

vector<int> vec{1, 2, 3, 0, 0, 0, 0, 0, 0, 0};

Which will give you a vector of 10 elements.

Or, you can create the vector, then call resize to make it larger (filling the remaining elements with 0):

vector<int> vec{1, 2, 3};
vec.resize(10);

You generally don't need to do this kind of thing to vector though, because unlike array, you can extend vector as needed, after creation:

vector<int> vec{1, 2, 3};
vec.push_back(4);
like image 161
CoffeeTableEspresso Avatar answered Sep 04 '25 21:09

CoffeeTableEspresso