This post will discuss how to initialize a vector in C++.

There are several ways to initialize a vector in C++, as shown below:

1. Using Initializer List

In C++11 and above, we can use the initializer lists '{...}' to initialize a vector. This won’t work in C++98 as standard allows the vector to be initialized by a constructor and not by '{...}'.

Download  Run Code

Output:

1 2 3 4 5

2. Using Copy Constructor

We can use a copy constructor to initialize the vector from another vector elements, following the same order of elements.

Download  Run Code

Output:

1 2 3 4 5

3. Using Range Constructor

We can use a range constructor to initialize vectors from elements of an array or another container.

Download  Run Code

Output:

1 2 3 4 5

4. Using Fill Constructor

We can use a fill constructor to initialize a vector of specified size by specified element.

Download  Run Code

Output:

1 1 1 1 1

5. Using Default Constructor

Finally, we can use the empty container constructor (or a default constructor) to construct an empty vector (with no elements), as shown below:

Download  Run Code

That’s all about initializing a vector in C++.