C++ Convert Array to Vector

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.

Example 1 – Convert Array to Vector using 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.

C++ Program

#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

Example 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.

C++ Program

#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.

Example 3 – Convert Array to Vector using Loop

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().

C++ Program

#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.