In this article we will discuss different ways to initialize a std::vector in C++.

Initializing std::vector elements with same value

It will create a vector of 5 element and initialize  each element is initialized to 10.

Initializing std::vector elements with passed argument list

It will create a vector of 5 element with given values. Will work with C++11 only.

Initializing std::vector from an array

It will initialize a vector through a range in array  or any other vector.

Initializing std::vector with Custom Calculated Values using std::generate

Suppose we want to initialize a vector with odd values from a given range only. This kind of functionality can be achieved using STL Algorithm std::generate and any user specific Function Object.


Let’s first create a function object that will give the next Odd number from a given range in each call.

Now lets use this Function Object with STL Algorithm std::generate to initialize the values of a vector.

Complete Working Code is as follows,

To compile the above code use following command,

g++ –std=c++11 vec_init.cpp


10 , 10 , 10 , 10 , 10 ,
10 , 20 , 30 , 40 , 50 ,
2 , 3 , 4 , 5 ,
11 , 13 , 15 , 17 , 19 ,

Click Here to Subscribe for more Articles / Tutorials like this.