In this C++ tutorial, you will learn how to convert an array into a vector, or create a vector from the elements of given array, using vector constructor, or looping statement, with examples.

Convert Array to Vector in C++

To convert an array to vector, you can use the constructor of Vector, or use a looping statement to add each element of array to vector using push_back() function.

1. Convert array to vector using vector constructor

You can convert an array to vector using vector constructor. Pass iterators pointing to beginning and ending of array respectively. The vector shall be initialized with the element of array.

main.cpp

</>
Copy
#include <iostream>
#include <vector>
using namespace std;

int main() {
   int numsArr[] = {2, 5, 1, 8, 4, 3, 6};
   vector<int> nums(begin(numsArr), end(numsArr));

   for (int i = 0; i < nums.size(); i++) {
      cout << nums[i] << endl;
   }     
}

Output

2
5
1
8
4
3
6

2. Convert part of array to vector

In the previous example, we have passed the beginning and ending pointers of array, and all the elements of array are copied to vector. You can control what range of elements in the array has to be copied to vector.

In the following example, we have an array with seven elements. We shall copy only the elements from index 2 to 5. To achieve that, instead of passing beginning and ending pointers, we shall modify them with the index range as shown in the example.

main.cpp

</>
Copy
#include <iostream>
#include <vector>
using namespace std;

int main() {
   int numsArr[] = {2, 5, 1, 8, 4, 3, 6};
   vector<int> nums(begin(numsArr)+2, begin(numsArr)+5);

   for (int i = 0; i < nums.size(); i++) {
      cout << nums[i] << endl;
   }     
}

Output

1
8
4

Only three elements in the range of [2, 5) of source array are converted to vector.

3. Convert array to vector using loop statement

You can also use a looping statement to push elements of array, one by one, into vector.

In the following example, we shall use C++ For Loop, to add elements of array to vector using push_back().

main.cpp

</>
Copy
#include <iostream>
#include <vector>
using namespace std;

int main() {
   int numsArr[] = {2, 5, 1, 8, 4, 3, 6};
   int len = end(numsArr) - begin(numsArr);
   
   vector<int> nums;
   for (int i=0; i < len; i++) {
      nums.push_back(numsArr[i]);
   }

   for (int element : nums) {
      cout << element << endl;
   }     
}

Output

2
5
1
8
4
3
6

Conclusion

In this C++ Tutorial, we learned how to Convert Array to Vector in C++, with the help of example programs.