How to Copy a Vector to an Array in C++?
In C++, vectors are dynamic arrays that can grow and reduce in size as per requirements. Sometimes, we may need to copy the contents of a vector to the POD array. In this article, we will learn how to copy a vector to an array in C++.
Example:
Input:
myVec = {10,20,30,40,50,60};
Output:
array: {10,20,30,40,50,60}
Convert Vector to an Array in C++
For copying the elements stored in a std::vector to an array in C++, we can use the std::copy()
function provided in the STL <algorithm>
library that copies a range of elements from one container to another.
Syntax to of std::copy()
copy (first, last, result);
Here,
- first is the iterator to the beginning of the vector.
- last is the iterator to the end of the vector.
- result is the iterator to the beginning of the array.
C++ Program to Copy a Vector to an Array
The below program demonstrates how we can copy a vector to an array using copy() in C++.
// C++ program to illustrate how to copy a vector to an
// array
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
// Driver code
int main()
{
// Vector
vector<int> vec = { 10, 20, 30, 40, 50, 60 };
// Print the vector
cout << "Vector: ";
for (int i = 0; i < vec.size(); i++)
cout << vec[i] << " ";
cout << endl;
// Array to store the vector elements
int arr[vec.size()];
// Copy vector to array
copy(vec.begin(), vec.end(), arr);
// Print the array
cout << "Array: ";
for (int i = 0; i < vec.size(); i++)
cout << arr[i] << " ";
cout << endl;
return 0;
}
Output
Vector: 10 20 30 40 50 60 Array: 10 20 30 40 50 60
Time Complexity: O(N), here N is the size of the vector.
Auxiliary Space: O(1)