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

Creating a vector object without any initialization will create an empty vector with no elements i.e.

But we generally want to initialize a vector with huge values and calling push_back() that many times to add element in vector is not an efficient and intelligent solution. So, let’s discuss how to initialize a vector in different ways,

Initializing a vector with default value of elements

Vector provides a constructor that accepts the size as an argument and initialize the vector with that many objects of default value i.e.

Output:

Initialize a vector by filling similar copy of an element

Many times we want to initialize a vector with an element of particular value instead of default value. For that vector provides an overloaded constructor i.e.

It accepts the size of vector and an element as an argument. Then it initializes the vector with n elements of value val.

Lets see an example that how to initialize a vector of std::string to 5 string objects with value “Hi”.

 Output:

Initialize a vector with an array

In above two examples we saw how to initialize a vector with same kind of value either default value or a particular value. But what if we want to initialize a vector with an array of elements. For that vector provides an over loaded constructor i.e.

It accepts a range as an argument i.e. two iterators and initializes the vector with elements in range (first, last] i.e. from first till last -1.

We will use the same overloaded constructor to initialize a vector of string from an array of strings i.e.

Output:

Initialize a vector with std::list

We will use the same overloaded constructor of std::vector to initialize a vector with range i.e.

This time range will be of std::list’s iterator i.e.

Output:

Initializing a vector with an other vector

Vector provides a constructor that receives other vector as an argument and initializes the current vector with the copy of all elements of provided vector i.e.

Lets how to initialize a vector of string with another vector of same type i.e.

Complete code with all 5 different ways to initialize a vector is as follows,