This post will discuss how to create an empty vector of initial size in C++.

1. Using fill constructor

A simple solution to construct a vector of custom size is using the fill constructor. It takes the initial vector size and initializes it with the specified value (or the default one).

For example, the following code constructs a vector with n elements, where each element is initialized with the default value of 0.

Download  Run Code

Output:

0 0 0 0 0

2. Using std::vector::reserve

To request a change in the capacity of a vector, we can use the std::vector::reserve function. It allocates enough space for the specified number of elements, which results in subsequent push_back operations being fast. Note that the std::vector::reserve function does not modify the size of a vector.

Download  Run Code

That’s all about creating an empty vector of initial size in C++.