How to initialize a vector in C++

A vector is a dynamic array class implemented in the standard C++ library. This vector ​class has the ability to dynamically grow and shrink. The elements are placed in a contiguous fashion so that they can be traversed by iterators.

The very first step in using vectors is to learn how to declare and initialize them; there are four​ ways of initializing a vector in C++:

1. Pushing the values one-by-one

All the elements that need to populate a vector can be pushed, one-by-one, into the vector using the vector class method​ push_back. The push-back method is shown in the code below:

#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> vec;
vec.push_back(1);
vec.push_back(2);
vec.push_back(3);
vec.push_back(4);
vec.push_back(5);
for (int i = 0; i < vec.size(); i++)
{
cout << vec[i] << " ";
}
return 0;
}

2. Using the overloaded constructor of the vector class

This method is mainly used when a vector is to be populated with multiple elements of the same value (e.g., if a vector needs to be populated with ten 1s)​. Take a look at the code below:

#include <iostream>
#include <vector>
using namespace std;
int main() {
int num_of_ele = 10;
// the overloaded constructor takes the number of
// values and the value itself as parameters.
vector<int> vec(num_of_ele, 1);
for (int i = 0; i < vec.size(); i++)
{
cout << vec[i] << " ";
}
return 0;
}

3. Using arrays

This method passes an array to the constructor of the vector class. The array contains the elements which will populate the vector. This method is shown in the code below:

#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> vec{1,2,3,4,5};
for (int i = 0; i < vec.size(); i++)
{
cout << vec[i] << " ";
}
return 0;
}

4. Using another, already initialized, vector

This method passes the begin() and end() iterators of an already initialized vector to a vector class constructor; a new vector is then initialized and​ populated by the elements in the old vector. Take a look at the​ code below:

#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> vec_1{1,2,3,4,5};
vector<int> vec_2(vec_1.begin(), vec_1.end());
for (int i = 0; i < vec_2.size(); i++)
{
cout << vec_2[i] << " ";
}
return 0;
}

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved