In this article, we will learn How to initialize a vector in C++? In C++, you can use the std::vector class to create a vector (a dynamic array).

To initialize a vector, you can use the default constructor, which creates an empty vector, or you can use one of the other constructors to create a vector with a specific size or with a set of initial values.

Examples of how to initialize a vector in C++


#include <vector>

// Default constructor: creates an empty vector
std::vector<int> v1;

// Constructor with size: creates a vector with a specific size (all elements are default-initialized)
std::vector<int> v2(5);

// Constructor with size and value: creates a vector with a specific size and initializes all elements with a given value
std::vector<int> v3(5, 10);

// Constructor with initializer list: creates a vector with a set of initial values
std::vector<int> v4 = {1, 2, 3, 4, 5};

In the first example, the default constructor is used to create an empty vector v1 of type int.

In the second example, the constructor with the size is used to create a vector v2 with 5 elements, all of which are default-initialized to 0.

In the third example, the constructor with size and value is used to create a vector v3 with 5 elements, all of which are initialized to the value 10.

In the fourth example, the constructor with an initializer list is used to create a vector v4 with the given initial values.

You can also use the resize method to change the size of an existing vector, and the push_back method to add new elements to the end of the vector.

Finally, Let us know in the comments if you like this tutorial on How to initialize a vector in C++